如何在nodejs中执行顺序基本命令?

问题描述 投票:0回答:2

我需要在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
2个回答
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/shelljshttps://www.npmjs.com/package/exec-sh

也可以promisify exechttps://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');
...
})();


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(async (p, c) => p.then(async () => await execAsync(c)), Promise.resolve());
© www.soinside.com 2019 - 2024. All rights reserved.