Search code examples
node.jsexpresschild-processspawn

Nodejs: how to check if spawn is successfull?


I am spawing a command from my express script, but I need to distinguish between error and success. I was looking for a child.on('success'...) function, but it doesn't exist.

This piece of code (of course) doesn't work.

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"});

 });

In other words, I need to fire the correct response only, not both!


Solution

  • 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)) ;
    });