Redirect Output to a File in Node.js

Create a writeable stream using fs.createWriteStream with the a (append) flag:

const fs = require('fs');
const { spawn } = require('child_process');

const logging = fs.createWriteStream('yourfile.log', { flags: 'a' });

const lsProcess = spawn('ls', ['-lh', '/etc']);

ls.on('close', code => {

Note that it is unsafe to use fs.write multiple times on the same file without waiting for its callback. For this scenario, fs.createWriteStream should be used.