How to execute shell command in Javascript

I’ll answer assuming that when the asker said “Shell Script” he meant a Node.js backend JavaScript. Possibly using commander.js to use frame your code 🙂

You could use the child_process module from node’s API. I pasted the example code below.

var exec = require('child_process').exec;

exec('cat *.js bad_file | wc -l',
    function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
             console.log('exec error: ' + error);
        }
    });

Hope this helps!

Leave a Comment