Run a Shell Script from NodeJs

posted by Jake on

NodeJs can do many things. It can even run things that it can't do itself. For instance, I have a shell script that I don't want to rewrite in Javascript, so I want my Node app to run the shell script. No problemo.

The docs indicate a number of ways you can kick off child processes. In my case, I wanted to use spawn.

Import the child_process library:

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

Now you have spawn available to call. Just send it the right stuff. I have a script that I want to run. The command I'll actually run is sh, and I'll pass the name of the script to it in the 2nd parameter. I can also specify other options in the 3rd parameter. For instance, I want this to execute in a certain directory and with certain commands available to it via the PATH variable. And so:

var _ = require('underscore'); // for some utility goodness
var deploySh = spawn('sh', [ '' ], {
  cwd: process.env.HOME + '/myProject',
  env:_.extend(process.env, { PATH: process.env.PATH + ':/usr/local/bin' })

This will execute the shell script. There are other callback events that you may/not want to set to grab the data that comes back from the process, such as 'data', 'end', or 'exit'.

Rock that!

Share the delectableness

About Jake Trent

Jake wrestles mean codes during the day, comes home to his beautiful wife, superstar son and delightful daughter in the evenings, and enjoys every day of it. RockyCode is one of his brain children, a prize of battle, won after a legendary struggle with his innermost thoughts and unwieldy hex digits. More by Jake

Leave a comment

blog comments powered by Disqus