【问题标题】:node js: child_process.exec not actually waiting节点 js:child_process.exec 实际上没有等待
【发布时间】:2022-01-25 22:12:51
【问题描述】:

请考虑这段代码:

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

它会下载一个 .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) 实际上并没有等待命令完成。是因为它是管道吗?

【问题讨论】:

标签: node.js async-await


【解决方案1】:

那么 exec 并不是真的那样工作。

await 关键字期望 Promise 等待。由于 exec 只会返回一个子进程对象,并且需要调用一个回调然后准备好,这不会起作用。

但是 node 中有一个 util 可以将这些常规的 node 函数转换为称为 util.promisify 的 Promise 函数。 nodejs.org/api/util.html#util_util_promisify_original

这也显示在 exec 的文档中(参见本段末尾的https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

let util = require('util')
let exec = require('child_process').exec
let exec_prom = util.promisify(exec)

exec_prom('ip address').then(()=>{console.log('done')})


async function do(){
  await exec_prom('ip address');
  // do something after
}

【讨论】:

    【解决方案2】:

    Node.js 有synchronous process creation:

    child_process.execFileSync(file[, args][, options])
    child_process.execSync(command[, options])
    child_process.spawnSync(command[, args][, options])
    

    execSync 是异步exec 的同步对应物:

    child_process.execSync() 方法通常与 child_process.exec() 除了该方法不会 返回,直到子进程完全关闭。

    只需使用这些函数等待命令的结果。

    const { execSync } = require('child_process');
    
    try {
        const result = execSync(cmd);
    }
    catch(error) {
        console.log(error);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多