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

50,104

Solution 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

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

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();
Share:
50,104
FredTheWebGuy
Author by

FredTheWebGuy

I am a senior software developer in the supply chain industry.

Updated on January 05, 2021

Comments

  • FredTheWebGuy
    FredTheWebGuy over 3 years

    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?

  • Adam Marsh
    Adam Marsh over 3 years
    This resolved the brick wall I was hitting! Thanks :)
  • AmirHossein Rezaei
    AmirHossein Rezaei about 2 years
    get function is not defined in newer version. New exmaple can be found here npmjs.com/package/node-cmd