Executing Shell Scripts With NodeJS Image Executing Shell Scripts With NodeJS

One of the problems I’ve been faced with recently is how do I go about executing shell scripts using NodeJS. This essentially allows me to query the status of certain processes and utilize the full power of the unix shell commands.

Implementation using NodeJS child_process Module

Node thankfully already has a module which is designed specifically for executing shell scripts and can be found here in the documentation.

This module essentially creates a child process in which we can execute our shell script and also sets everything up for us so that we can utilize stdin, stdout and stderr within our NodeJS application.

Executing Unix or Windows Commands

We can use the exec function to run a wide range of windows and unix commands and also pass any number of arguments to this command should we need to.

const ls = spawn("ls", ["-lh", "/usr"]);

Whilst there may be times that we aren’t interested in the output of any of the commands that we run, more often than not we need to capture the output so that we can check that everything worked well.

const ls = spawn("ls", ["-lh", "/usr"]);

ls.stdout.on("data", function(data) {
  console.log(data);
});

ls.stderr.on("data", function(data) {
  console.log(data);
});

ls.on("close", function(code) {
  console.log(`child process exited with code ${code}`);
});

Executing Shell Scripts

In the below example you’ll see how we can utilize callbacks in order to access the data from stdout and stderr and subsequently view any errors and output our shell scripts output.

const exec = require('child_process').exec, child;
const testscript = exec('sh myscript.sh /directory');

testscript.stdout.on('data', function(data){
    console.log(data);
    // sendBackInfo();
});

testscript.stderr.on('data', function(data){
    console.log(data);
    // triggerErrorStuff();
});

Conclusion

Through this method I was able to wrap some pretty mundane and annoying scripts in an automated fashion and tie them together in a concise and automated fashion. This helped to reduce the amount of time spent configuring the scripts and allowed me to focus more on the results.

I hope you found this tutorial useful, if you need anything further explained then please feel free to reach out to me in the comments section below!

Elliot Forbes

Elliot Forbes
Twitter: @Elliot_f

Hey, I'm Elliot and I've been working on TutorialEdge for the last 4 years! If you have any tips or suggestions as to how I can make it better, please let me know in the suggestion box below!

Comments Section