子进程退出后,节点不发送响应

时间:2018-03-19 08:40:44

标签: node.js express child-process

我有以下路线:

app.get('/downloadSentinel', function (req,res){
var promObj = {};
var data = req.query.data;
var Name = req.query.name;
namesArray = [];
for(var i =0;i<Name.length;i++){
    namesArray.push(Name[i]);
}
promObj['Name'] = namesArray;
console.log(promObj.Name);
requestarray = [];
for (i=0; i<data.length;i++) {
    requestarray.push(data[i]);
    promObj['requestURLS'] = requestarray;
}

createResultFolder(promObj)
   .then(downloadSentinel)
.then(resp => {
    console.log("THEN:", resp);
    res.send(resp);
}).catch((err) => {
    console.log("CATCH:", err)
   res.send(err);

})

});

函数downloadSentinel调用Node子进程,如下所示:

function downloadSentinel(promObj){
    return new Promise((resolve,reject) =>{
        var sys = require('util'),
            exec = require('child_process').exec,
            child;

        var urls = parseArrayForBash(promObj.requestURLS);
        var names = parseArrayForBash(promObj.Name);

            console.log("executing:", './downloadProducts.sh ' + urls + ' ' + names);
            child = exec('bash downloadProducts.sh '+ urls + ' ' + names, [{stdio:'inherit'}]);

            child.stderr.pipe(process.stderr);
            child.stdout.pipe(process.stdout);

            child.on("error", function (error) {
                console.log("child error:", error);
                reject(promObj)
            })

            child.on('data', function (data) {
                console.log(data.toString());

            });

            child.on('exit', function (exit) {
                console.log("child exit:", exit);
                resolve(promObj);
            })
        }
    })
 }

downloadSentinel的输出是:

child exit: 0
THEN: { Name:
[ 'S2A_MSIL1C_20180315T041541_N0206_R090_T46QEH_20180315T075531',
 'S2A_MSIL1C_20180315T041541_N0206_R090_T46QEK_20180315T075531' ],
requestURLS:
[ 'bb5f4946-ce18-4b50-97ba-7ac9a94d9f1e',
 'ec15c5d4-0cc6-44d4-a11f-6c2e9055f2e4' ] }

所以我认为一切都按预期工作。但是在子进程退出代码0之后,响应res.send(resp);不会发送到客户端,我永远不会得到成功消息。

我做错了什么?

P.S。:对于大量代码感到抱歉,但我不知道自己做错了什么,所以我提供了所有内容。

修改 对于客户端部分,我正在使用此jQuery Ajax请求:

function downloadSentinelData(ID,Name){
var url = encodeURI('/downloadSentinel?');
$.ajax({
    type: 'GET',
    url:  url,
    timeout:5000,
    dataType:'json',
    data: {
        data: ID,
        name: Name
    },
    success: function(data,status){
        console.log(data);
        console.log(status);
        alert('Products downloaded. Processing now.');
    },
    error: function (errorMessage) {
    }
});
}

可能有错吗?

1 个答案:

答案 0 :(得分:0)

如果您使用的是express.js,则应在res.send之后执行res.end()