How to run cli/unix commands from nodejs scripts?

There are two ways to do this:


child_process.exec(command[, options][, callback])

// ls.js
const { exec } = require('child_process');
exec('ls -lh /usr', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

From CLI,

$ npm run-script ls


child_process.spawn(command[, args][, options])

// ls.js
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

From CLI,

$ npm run-script ls


You may also like...