在Node.js中,等待child_process退出的替代方案有以下几种:
示例代码:
const { spawn } = require('child_process');
const child = spawn('command');
child.on('exit', (code) => {
console.log(`子进程退出,退出码:${code}`);
// 在这里执行其他操作
});
示例代码:
const { spawn } = require('child_process');
function runCommand(command) {
return new Promise((resolve, reject) => {
const child = spawn(command);
child.on('exit', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`子进程退出,退出码:${code}`));
}
});
});
}
runCommand('command')
.then(() => {
console.log('子进程成功退出');
// 在这里执行其他操作
})
.catch((error) => {
console.error('子进程退出时发生错误:', error);
});
示例代码:
const { spawn } = require('child_process');
function runCommand(command) {
return new Promise((resolve, reject) => {
const child = spawn(command);
child.on('exit', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`子进程退出,退出码:${code}`));
}
});
});
}
async function main() {
try {
await runCommand('command');
console.log('子进程成功退出');
// 在这里执行其他操作
} catch (error) {
console.error('子进程退出时发生错误:', error);
}
}
main();
这些替代方案可以根据具体需求选择使用,以实现在Node.js中等待child_process退出的功能。
领取专属 10元无门槛券
手把手带您无忧上云