Skip to content

Instantly share code, notes, and snippets.

@sefgit
Created March 8, 2025 05:16
Show Gist options
  • Save sefgit/35f5da1eca6f0336fdee2cb74d1c3fdb to your computer and use it in GitHub Desktop.
Save sefgit/35f5da1eca6f0336fdee2cb74d1c3fdb to your computer and use it in GitHub Desktop.
redirect output to file
//
// https://zaiste.net/programming/nodejs/howtos/redirect-output-to-file-nodejs/
//
const fs = require('fs');
const { spawn } = require('child_process');
const logging = fs.createWriteStream('yourfile.log', { flags: 'a' });
const lsProcess = spawn('ls', ['-lh', '/etc']);
ls.stdout.pipe(logging);
ls.stderr.pipe(logging);
ls.on('close', code => {
console.log(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.
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment