Is it possible to execute an external program from within node.js? Is there an equivalent to Python's os.system()
or any library that adds this functionality?
Asked
Active
Viewed 1.5e+01k times
156

jww
- 97,681
- 90
- 411
- 885

Michael Bylstra
- 5,042
- 4
- 28
- 24
-
You want to use the `child_process` module. See [the documentation](http://nodejs.org/api/child_process.html), which provides several clear examples of various use cases. – kqnr Apr 25 '11 at 04:15
5 Answers
151
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr) {
// result
});

Cody Gray - on strike
- 239,200
- 50
- 490
- 574
-
2What's the best way to act on a result of the child process. Example... if the process returns an exit code 0, and I want to call a different method, I seem to run into a plethora of errors. – continuousqa Mar 20 '15 at 23:59
-
@continuousqa -- This answer is 4 years old. If you are having issues, please post a new question on SO and reference this one if necessary. – Mar 21 '15 at 06:02
-
1This [article](https://medium.com/@graeme_boy/how-to-optimize-cpu-intensive-work-in-node-js-cdc09099ed41#.se7f974h7) has good tips on using `child_process`. – Adriano P Jun 02 '16 at 21:17
88
exec has memory limitation of buffer size of 512k. In this case it is better to use spawn. With spawn one has access to stdout of executed command at run time
var spawn = require('child_process').spawn;
var prc = spawn('java', ['-jar', '-Xmx512M', '-Dfile.encoding=utf8', 'script/importlistings.jar']);
//noinspection JSUnresolvedFunction
prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
var str = data.toString()
var lines = str.split(/(\r?\n)/g);
console.log(lines.join(""));
});
prc.on('close', function (code) {
console.log('process exit code ' + code);
});

MKK
- 2,431
- 20
- 16
-
1I took this code and it fails to show output of spawned process http://stackoverflow.com/questions/21302350/node-js-cant-get-output-of-spawned-process – Paul Verest Jan 23 '14 at 07:58
-
1@PaulVerest: Your output may have been in `stderr` rather than `stdout`. In my case though the `close` is never coming ... – hippietrail Nov 19 '17 at 22:15
-
1
5
From the Node.js documentation:
Node provides a tri-directional popen(3) facility through the ChildProcess class.

Michelle Tilley
- 157,729
- 40
- 374
- 311
0
Using import statements with utils promisify:
import { exec } from 'child_process';
import utils from 'util';
const execute = utils.promisify(exec);
console.log(await execute('pwd'));

Wtower
- 18,848
- 11
- 103
- 80