I have a script written in Node to handle some basic server operations. I am then using the node-windows package to run this script as a service. A part of this script writes to a log file. Everything works fine when running the script normally through a command line. But when running as a service nothing gets written to the log file. Initially I thought it might be a pathing issue but this doesn't seem to be the case. Has anyone else had experience with this and do you have any suggestions on how to resolve this?
When using 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()
. So if your log path is relative you will run into this issue. I would suggest making the directory where your NodeJS application resides an Environment Variable within your node-windows
install script. The benefit of doing that is you can reference the Environment variable to get the absolute path to your directory and then prefix your log path with the value returned from the Environment Variable. See below code sample.
'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();
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);
}