How to execute an external program from within Node.js?

node.jsCommandExec

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr) {
  // result
});

Solution 2 - node.js

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

Solution 3 - node.js

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

Solution 4 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael BylstraView Question on Stackoverflow
Solution 1 - node.jsNoneView Answer on Stackoverflow
Solution 2 - node.jsMKKView Answer on Stackoverflow
Solution 3 - node.jszag2artView Answer on Stackoverflow
Solution 4 - node.jsMichelle TilleyView Answer on Stackoverflow