【问题标题】:How to execute sequential base commands in nodejs?如何在nodejs中执行顺序基本命令?
【发布时间】:2019-12-02 07:09:48
【问题描述】:

我需要在 nodejs 中依次运行 4 个 bash 命令。

set +o history
sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js
sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js.map
set -o history

如何做到这一点?或者是否可以在 npm 脚本中添加?

【问题讨论】:

标签: javascript node.js npm npm-scripts


【解决方案1】:

要扩展@melc 的答案,按顺序执行请求,您可以这样做:

const {promisify} = require('util');
const {exec} = require('child_process');
const execAsync = promisify(exec);

const sequentialExecution = async (...commands) => {
  if (commands.length === 0) {
    return 0;
  }

  const {stderr} = await execAsync(commands.shift());
  if (stderr) {
    throw stderr;
  }

  return sequentialExecution(...commands);
}

// Will execute the commands in series
sequentialExecution(
  "set +o history",
  "sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js",
  "sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js.map",
  "set -o history",
);

或者如果你不关心stdout/sterr,你可以使用下面的单行:

const commands = [
  "set +o history",
  "sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js",
  "sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js.map",
  "set -o history",
];

await commands.reduce((p, c) => p.then(() => execAsync(c)), Promise.resolve());

【讨论】:

    【解决方案2】:

    要从节点运行 shell 命令,请使用exechttps://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

    三种可能的方法是,

    1. 创建一个包含所有需要命令的 bash 脚本文件,然后使用 exec 从节点运行它。

    2. 使用exec从节点单独运行每个命令。

    3. 使用 npm 包,例如以下之一(我没有尝试过) https://www.npmjs.com/package/shelljs
      https://www.npmjs.com/package/exec-sh

    也可以使用promisify exec (https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original) 并使用async/await 代替回调。 例如,

    const {promisify} = require('util');
    const {exec} = require('child_process');
    
    const execAsync = promisify(exec);
    
    (async () => {
      const {stdout, stderr} = await execAsync('set +o history');
    ...
    })();
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多