我需要在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脚本?
要从节点运行shell命令,请使用exec
,https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
可能的三种方法,
创建包含所有必需命令的bash脚本文件,然后使用exec
从节点运行它。
使用exec
从节点单独运行每个命令。
使用npm软件包,例如以下之一(我没有尝试过)https://www.npmjs.com/package/shelljshttps://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');
...
})();
要扩展@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());