【问题标题】:Node exec bash commands after finishing first command完成第一个命令后节点执行 bash 命令
【发布时间】:2020-08-12 19:39:17
【问题描述】:

使用 Node 自动化我的一些 bash 进程。

const { exec } = require("child_process");

let buildCommand = "docker build -t vm1:v1 ./nginx1 " 
let runCommand = "docker run -d -p 6001:6001 --name clientvm1 vm1:v1"


//run first command

 exec(buildCommand, (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

//run second command

   exec(runCommand, (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

让第二个命令等到第一个命令完成的最佳方法是什么?

【问题讨论】:

    标签: node.js bash terminal


    【解决方案1】:

    我当然不是专家,但也许您可以将第二种方法包装在异步方法中并在其中等待第一种方法?

    method1() {
      return new Promise((resolve, reject) => {
        resolve(exec(buildCommand));
      }).catch((err) => throw new Error(err));
    }
    
    async method2() {
      await method1();
      exec(runCommand);
    }
    

    这可能远非万无一失,但我认为它应该可以满足您的需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 2017-12-20
      相关资源
      最近更新 更多