Search code examples
node.jscmdwindows-shell

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

  • 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));
    

    It does not support Promises directly, but you can easily wrap them inside one:

    const nodeCmd = require('node-cmd');
    const promise = new Promise((resolve, reject) => {
        nodeCmd.run('dir', (err, data, stderr) => {
            if (err) {
                reject(err);
            } else {
                resolve(data, stderr);
            }
        });
    });