Search code examples
node.jsspawn

How to detect if a Node spawned process is still running?


I can spawn a process like:

var spawn = require('child_process').spawn;

var topicListener = spawn('python', ['topic_listener.py','Node.js'], {env: {
    TWITTER_CONSUMER_SECRET: process.env.TWITTER_CONSUMER_SECRET,
    TWITTER_CONSUMER_KEY: process.env.TWITTER_CONSUMER_KEY,
    TWITTER_TOKEN_SECRET: process.env.TWITTER_TOKEN_SECRET,
    TWITTER_ACCESS_TOKEN: process.env.TWITTER_ACCESS_TOKEN
}});

topicListener.stdout.on('data', function (data) {
    console.log(data.toString());
});

topicListener.stderr.on('data', function (data) {
    console.log(data.toString());
});

topicListener.on('close', function (code) {
    console.log("EXITED " + code);
});

So of course I can control it all asycnchronously with .on(close, ...) but is there any other way to control if a process is still alive?


Solution

  • spawn('python', ['topic_listener.py','Node.js'].. Return Child process Object. Use topicListener.pid to find unique ID associated with the process if it's alive.