159

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?

1
  • You want to use the child_process module. See the documentation, which provides several clear examples of various use cases. Commented Apr 25, 2011 at 4:15

5 Answers 5

152
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr) {
  // result
});
Sign up to request clarification or add additional context in comments.

3 Comments

What'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 -- This answer is 4 years old. If you are having issues, please post a new question on SO and reference this one if necessary.
This article has good tips on using child_process.
88
+500

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);
});

3 Comments

I took this code and it fails to show output of spawned process stackoverflow.com/questions/21302350/…
@PaulVerest: Your output may have been in stderr rather than stdout. In my case though the close is never coming ...
what about stdin? is it possible to send data to the process?
22

The simplest way is:

const { exec } = require("child_process")
exec('yourApp').unref()

unref is necessary to end your process without waiting for "yourApp"

Here are the exec docs

Comments

5

From the Node.js documentation:

Node provides a tri-directional popen(3) facility through the ChildProcess class.

See http://nodejs.org/docs/v0.4.6/api/child_processes.html

Comments

2

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'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.