Node.js 节点js:child_process.exec未实际等待 请考虑这段代码: var cmd = `cd "${dir}" && curl -L "${url}" | tar -xJvf - | zip -qr archive.zip -@`; await exec(cmd); res.sendFile(path.join(dir, "archive.zip"));

Node.js 节点js:child_process.exec未实际等待 请考虑这段代码: var cmd = `cd "${dir}" && curl -L "${url}" | tar -xJvf - | zip -qr archive.zip -@`; await exec(cmd); res.sendFile(path.join(dir, "archive.zip"));,node.js,async-await,Node.js,Async Await,它下载一个.tar.xz,解压并重新压缩,最后发送给用户 如果我运行它,它会在res.sendFile(…)处失败,表示该文件不存在。但是,如果我查看我的文件系统,zip实际上就在那里 因此,我尝试在res.sendFile(…)之前添加一个小延迟,如下所示: var cmd = `cd "${dir}" && curl -L "${url}" | tar -xJvf - | zip -qr archive.zip -@`; await exec(cmd); setTimeou

它下载一个.tar.xz,解压并重新压缩,最后发送给用户

如果我运行它,它会在
res.sendFile(…)
处失败,表示该文件不存在。但是,如果我查看我的文件系统,zip实际上就在那里

因此,我尝试在
res.sendFile(…)
之前添加一个小延迟,如下所示:

var cmd = `cd "${dir}" && curl -L "${url}" | tar -xJvf - | zip -qr archive.zip -@`;
await exec(cmd);

setTimeout(()=>{
    res.contentType(path.join(dir, "archive.zip"));
    res.sendFile(path.join(dir, "archive.zip"));
}, 1000);
…它神奇地工作了


似乎
exec(cmd)
实际上并不等待命令完成。是因为它是通过管道传输的吗?

Well exec并不是这样工作的

wait关键字需要等待一个承诺。因为exec只返回一个子进程对象,并且需要调用回调然后准备就绪,所以这不起作用

但是节点中有一个util,用于将这些常规节点函数转换为名为util.promisify的promise函数

exec的文档中也显示了这一点(见本段末尾)

let util=require('util'))
让exec=require('child_process')。exec
让exec_prom=util.promisify(exec)
exec_prom('ip address')。然后(()=>{console.log('done')})
异步函数do(){
等待exec_prom(“ip地址”);
//事后做某事

}
exec很可能不返回承诺,但需要在完成时触发回调。请看:啊,是的!我真丢脸!谢谢