如何在node.js中杀死child_process - req.on close

时间:2014-06-02 19:24:37

标签: javascript node.js callback kill child-process

我试图在" requst.on(' close'"被调用)时杀死子进程。但是这个回调中的child.pid总是指向最近的请求。问题是:如何将child.pid与请求匹配?谢谢

var query_script = "query.py"
var express = require('express');
var app = express();
var spawn = require('child_process').spawn;

app.get('/:version/query', function(request, response) {
    child = spawn('python, ['query.py', request.originalUrl])
    console.log("start pid=" + child.pid + ": " + request.originalUrl)

    request.on('close', function () {
        console.log("1: current pid=" + child.pid)    
        //child.kill('SIGTERM');
    })

    child.stdout.pipe(response)
});

app.listen(3000);
console.log('Listening on port 3000...');

1 个答案:

答案 0 :(得分:1)

通过在其前面放置child来定义闭包中的var

var child = spawn('python, ['query.py', request.originalUrl])