user5325622
user5325622

Reputation: 5

Execute multiple shell commands in Node.js

I want to execute multiple Shell commands from a node.js application consecutively. In my case, exec(command1 & command2) does not work as it should. It works for simple commands like ls and pwd, but I need to start a server and then execute special commands on it and there, it only executes the very first command and nothing more. When I work on my command-line interface, I just type in one command after the other and I need a facility to execute them in the same manner, but automatically starting from a node.js application - and all of them in the same process!

Upvotes: 1

Views: 3531

Answers (1)

user5283155
user5283155

Reputation:

You could use child_process module to achieve that.

Here's an example code to demonstrate the usage

var child_process = require('child_process');

var task1 = child_process.exec('node --version', function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
        console.log('exec error: ' + error);
    }
});

var task2 = child_process.exec('npm --version', function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
        console.log('exec error: ' + error);
    }
});

Upvotes: 3

Related Questions