替代等待child_process退出node.js

时间:2017-02-16 03:21:33

标签: node.js express

我已经在1个脚本中运行了这两个代码:

ping脚本:

app.get("/ping", function(req, res) {
    res.send("Pong!");
});

正在进行的工作youtube downloader:

app.post("/nodedl", function(req, res) {
 res.write("===Gradyncore listnener===\n")
 res.write("Recived POST request from "+req.ip+" to /nodedl\n")
 res.write("POST(url): "+req.body.url+"\n")
 res.write("checking key...\n")
 if (req.body.key==="<Insert key here>"){
   res.write("Key is valid! Skipping pre-download script...\n")
 } else {
   res.write("Key is invalid. Running pre-download script...\n")
   exec("/home/gradyn/website/projects/nodeDL/scripts/check.sh", function (error, results) {
   if (results != null) {
        res.write(results+"\n");
   } else if (error != null) {
        res.write("Error: " + error+"\n");
  }
});
 }
res.end();
});

问题是,当check.sh完成时,res.end();已经发出了allredy,导致此错误,然后崩溃

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:15)
    at /home/gradyn/listener/app.js:29:13
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

我对node.js相当新,但据我所知,如果我在调用res.end()之前等待子进程完成,整个脚本(包括ping监听器)将无法正常工作直到子进程完成。

我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

问题是你的exec是异步的,下面的代码不会等到执行exec并执行...你必须在回调函数内结束响应:

app.post("/nodedl", function(req, res) {
    res.write("===Gradyncore listnener===\n")
    res.write("Recived POST request from "+req.ip+" to /nodedl\n")
    res.write("POST(url): "+req.body.url+"\n")
    res.write("checking key...\n")
    if (req.body.key==="<Insert key here>"){
        res.write("Key is valid! Skipping pre-download script...\n")
    } else {
       res.write("Key is invalid. Running pre-download script...\n")
       exec("/home/gradyn/website/projects/nodeDL/scripts/check.sh", function(error, results) {
           if (results != null) {
               res.write(results+"\n");
               res.end();
           } else if (error != null) {
               res.write("Error: " + error+"\n");
               res.end();
           }
        });
    }
});