Synchronous child process calls are now available in the versions of Node.js that are under development (i.e. unstable). This is great news for writing shell scripts, as it will allow code like this:
var history = child_process.execSync('git log', { encoding: 'utf8' });
process.stdout.write(history);
However, for code aimed at the current stable version of Node.js (v0.10.30), synchronous child process calls are not available except via external libraries. The two most popular such libraries appear to be shelljs and exec-sync.
For shell scripts intended for use with v0.10.x, and which must call binaries or other executables and process their output, what are the relative pros and cons of these two libraries or other comparable libraries? Please provide code samples for illustration, if appropriate.
Let's look at three options: the two mentioned in the question, plus execsync.
shelljs
is much more than a library for calling child processes. Primarily, it is a cross-platform JavaScript implementation of several POSIX utilities and shell builtins: >
, cat
, cd
, chmod
, cp
, dirs
, echo
, env
, exec
, exit
, find
, grep
, ln
, ls
, mkdir
, mv
, popd
, pushd
, pwd
, rm
, sed
, test
, which
. It also provides a couple of useful functions of its own: error()
and tempdir()
.
Its exec
function can be used to run an external executable synchronously.
Using global namespace:
require('shelljs/global');
var version = exec('node --version', {silent:true}).output;
console.log('version ' + version);
Alternatively, using local namespace:
var sh = require('shelljs');
var version = sh.exec('node --version', {silent:true}).output;
console.log('version ' + version);
exec-sync has been retired in favour of execSync. The rest of this section therefore refers to the latter.
The execSync library consists of a JavaScript wrapper around a C++ core. During the installation of execSync, the C++ core is compiled into a platform-appropriate NodeJS binary module.
var sh = require('execSync');
var version = sh.exec('node --version').stdout;
console.log('version ' + version);
Worth mentioning here as it is easily confused with execSync (see above) by any case-insensitive search engine, other algorithm, or human. Confusing matters further, the author of execsync has used the orthography "execSync" at a few points in execsync's code and documentation.
Like execSync above, the execsync library consists of a JavaScript wrapper around a C++ core. During the installation of execsync, the C++ core is compiled into a platform-appropriate NodeJS binary module.
var sh = require('execsync');
var version = sh('node --version');
console.log('version ' + version);