'How To Execute Windows Shell Commands (Cmd.exe) with Node JS

I would like to

C:\>ACommandThatGetsData > save.txt

But instead of parsing and saving the data in the console, I would like to do the above command with Node.JS

How to execute a shell command with Node.JS?



Solution 1:[1]

You could also try the node-cmd package:

const nodeCmd = require('node-cmd');
nodeCmd.get('dir', (err, data, stderr) => console.log(data));

On newer versions of the package, the syntax changed a little:

const nodeCmd = require('node-cmd');
nodeCmd.run('dir', (err, data, stderr) => console.log(data));

Solution 2:[2]

Use process.execPath():

process.execPath('/path/to/executable');

Update

I should have read the documentations better.

There is a Child Process Module which allows to execute a child process. You will need either child_process.exec, child_process.execFile or child_process.spawn. All of these are similar in use, but each has its own advantages. Which of them to use depends on your needs.

Solution 3:[3]

I know this question is old, but it helped me get to my solution using promises. Also see: this question & answer

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function runCommand(command) {
  const { stdout, stderr, error } = await exec(command);
  if(stderr){console.error('stderr:', stderr);}
  if(error){console.error('error:', error);}
  return stdout;
}


async function myFunction () {
    // your code here building the command you wish to execute ...
    const command = 'dir';
    const result = await runCommand(command);
    console.log("_result", result);
    // your code here processing the result ...
}

// just calling myFunction() here so it runs when the file is loaded
myFunction();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Adam Marsh