NodeJS 脚本 运行 作为 windows 服务。无法写入文件
NodeJS script running as a windows service. Cannot write to file
我有一个用 Node 编写的脚本来处理一些基本的服务器操作。然后我使用 node-windows 包来 运行 这个脚本作为服务。此脚本的一部分写入日志文件。 运行通过命令行正常运行脚本时一切正常。但是当 运行ning 作为服务时,没有任何内容写入日志文件。最初我认为这可能是一个路径问题,但事实并非如此。有没有其他人有过这方面的经验,您对如何解决这个问题有什么建议吗?
使用node-windows
, the path to where the log file is written should be absolute and not relative. This is because node-windows
wraps your code in a Daemon that then runs your code from its location, your code is run using child-process.fork()
时。因此,如果您的日志路径是相对的,您将 运行 陷入此问题。我建议在 node-windows
安装脚本中将 NodeJS 应用程序所在的目录设为环境变量。这样做的好处是您可以引用环境变量来获取目录的绝对路径,然后在日志路径前加上从环境变量返回的值。请参阅下面的代码示例。
install.js
'use strict';
const Service = require('node-windows').Service;
const path = require('path');
const svc = new Service({
name: 'Logger',
description: 'Log software',
script: path.join(process.cwd(), 'index.js'),
env: [
{
name: 'APP_DIR_PATH',
value: process.cwd()
}
]
});
svc.on('install', () => {
console.log(`${svc.name} installed`);
});
svc.on('alreadyinstalled', () => {
console.log(`{svc.name} already installed`);
});
svc.install();
app-logger.js
const appDir = process.env.APP_DIR_PATH;
const path = require('path');
const logPath = path.join(appDir, '/logs/log.txt');
const fs = require('fs');
module.exports = function insertLog(entryText, callback) {
let entry = { timestamp: (new Date()), text: entryText };
fs.appendFile(logPath, JSON.stringify(entry), callback);
}
我有一个用 Node 编写的脚本来处理一些基本的服务器操作。然后我使用 node-windows 包来 运行 这个脚本作为服务。此脚本的一部分写入日志文件。 运行通过命令行正常运行脚本时一切正常。但是当 运行ning 作为服务时,没有任何内容写入日志文件。最初我认为这可能是一个路径问题,但事实并非如此。有没有其他人有过这方面的经验,您对如何解决这个问题有什么建议吗?
使用node-windows
, the path to where the log file is written should be absolute and not relative. This is because node-windows
wraps your code in a Daemon that then runs your code from its location, your code is run using child-process.fork()
时。因此,如果您的日志路径是相对的,您将 运行 陷入此问题。我建议在 node-windows
安装脚本中将 NodeJS 应用程序所在的目录设为环境变量。这样做的好处是您可以引用环境变量来获取目录的绝对路径,然后在日志路径前加上从环境变量返回的值。请参阅下面的代码示例。
install.js
'use strict';
const Service = require('node-windows').Service;
const path = require('path');
const svc = new Service({
name: 'Logger',
description: 'Log software',
script: path.join(process.cwd(), 'index.js'),
env: [
{
name: 'APP_DIR_PATH',
value: process.cwd()
}
]
});
svc.on('install', () => {
console.log(`${svc.name} installed`);
});
svc.on('alreadyinstalled', () => {
console.log(`{svc.name} already installed`);
});
svc.install();
app-logger.js
const appDir = process.env.APP_DIR_PATH;
const path = require('path');
const logPath = path.join(appDir, '/logs/log.txt');
const fs = require('fs');
module.exports = function insertLog(entryText, callback) {
let entry = { timestamp: (new Date()), text: entryText };
fs.appendFile(logPath, JSON.stringify(entry), callback);
}