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);
});

Here's an example of logging to file using streams.

var logStream = fs.createWriteStream('./logFile.log', {flags: 'a'});

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

ls.stdout.pipe(logStream);
ls.stderr.pipe(logStream);

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

If you run your JS script with forever then you have the option to define a log file as parameter which will handle all your console.log messages. Not to mention the benefit of keeping your nodejs app live permanently.

Alternatively try this:

sudo forever start myapp.js 2>&1 /home/someuser/myapp/myapp.log

use forever with below options

forever start -o out.log -e err.log server.js

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!");
    }
});