gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:12 25 4
gpt4 key购买 nike

我需要在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 脚本中?

最佳答案

要扩展@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());

关于javascript - 如何在nodejs中执行顺序基本命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com