简体   繁体   English

在Node.js中执行多个Shell命令

[英]Execute multiple shell commands in Node.js

I want to execute multiple Shell commands from a node.js application consecutively. 我想从node.js应用程序连续执行多个Shell命令。 In my case, exec(command1 & command2) does not work as it should. 就我而言, exec(command1 & command2)无法正常工作。 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. 它适用于lspwd类的简单命令,但是我需要启动服务器,然后在该服务器上执行特殊命令,在那里,它仅执行第一个命令,仅此而已。 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! 当我在命令行界面上工作时,我只键入一个命令即可,并且我需要一种设施以相同的方式执行这些命令,但是需要自动从node.js应用程序启动-所有这些命令都在同一过程中!

You could use child_process module to achieve that. 您可以使用child_process模块来实现。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM