Nodejs:如何检查spawn是否成功?

Fab*_*cca 3 spawn child-process node.js express

我正在从我的快速脚本中生成命令,但我需要区分错误和成功。我正在寻找一个child.on('success'...)功能,但它不存在。

这段代码(当然)不起作用。

app.get(myID+'/test/', function(req, res){ 
        var child = spawn('lbg');
        child.on('error', function(err) {
                console.log('Failed to start child process.');  
                res.status(404).send("Cannot send test command");
                return;
        });
        res.json({statusMessage: "OK", statusCode: "200"});

 });
Run Code Online (Sandbox Code Playgroud)

换句话说,我只需要触发正确的响应,而不是两者都触发!

Yar*_*nov 6

app.get(myID+'/test/', function(req, res){ 
        var child = spawn('lbg');
        child.on('close', code => {
          if (code === 0) {
             res.json({statusMessage: "OK", statusCode: "200"});
          } else {
             res.status(404).send("Cannot send test command");
          }
        }).on('error', err => res.status(404).send(err)) ;
});
Run Code Online (Sandbox Code Playgroud)