gpt4 book ai didi

javascript - 如何在nodejs中同步执行?

转载 作者:行者123 更新时间:2023-11-30 14:41:41 25 4
gpt4 key购买 nike

我有以下代码。

router.post('/',function(req, res, next) {
var id=req.body.id;
console.log(id);

const testscript = exec('sh script.sh');

testscript.stdout.on('data', function(data){
console.log(data);
// sendBackInfo();
});

testscript.stderr.on('data', function(data){
console.log(data);
// triggerErrorStuff();
});

res.redirect('/Visualise');
});

我需要完全执行我的 shell 脚本,然后重定向到“/Visualise”。下一页中的部分代码使用了 shell 脚本生成的输出文件。它在完全执行 shell 脚本之前进行重定向,我收到一个找不到文件的错误。我怎样才能同步执行。为此,请对上述代码进行必要的更改。谢谢。

最佳答案

您真正想要的不是同步执行脚本,因为那样会阻塞事件循环并阻止其他请求运行。相反,您需要(异步地)等待脚本完成。

为此,将重定向写入子进程的 exit 事件中,而不是在处理程序的主体中:

router.post('/', function(req, res, next) {
// ...whatever

const testscript = exec('sh script.sh');

// ...stdouts

testscript.on('exit', function (code, signal) {
res.redirect('/Visualise');
});
});

关于javascript - 如何在nodejs中同步执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49550592/

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