Michael Bylstra
Michael Bylstra

Reputation: 5222

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

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?

Upvotes: 159

Views: 152827

Answers (5)

Wtower
Wtower

Reputation: 19902

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

Upvotes: 2

user578895
user578895

Reputation:

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

Upvotes: 152

zag2art
zag2art

Reputation: 5162

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

Upvotes: 22

MKK
MKK

Reputation: 2559

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

Upvotes: 88

Michelle Tilley
Michelle Tilley

Reputation: 159095

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

Upvotes: 5

Related Questions