Saturday 22 April 2017

Redirecting output to a log file using node.js



I have a child process that I am using as follows in node.js. Instead of redirecting the output to the console I would like to put the output in a log file located somewhere on the machine this is running on (and should work for both windows and mac).




The code below is what I am using and I would like to output the files into a log file. What changes needed to do that here? Thanks!



My Code:



var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});


ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});

ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});

Answer




The best answer was in the comments and is mentioned in a previous question here: stackoverflow.com/questions/2496710/nodejs-write-to-file



It is as follows:



var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");

}
});

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...