如果我在不同的文件中使用以下代码,则不会调用exec的回调函数。如果我在主文件中执行代码,它确实有效。
inConsole.js
static
第一个console.log可以工作,但回调中的第二个没有输出。
main.js
var exec = require('child_process').exec;
var log = require('../includes/log');
var errorCodes = {
30: "inEnterprise returned an error",
40: "Unable to connect to host",
41: "Unable to resolve hostname",
42: "Unable to create socket",
43: "Invalid port number",
44: "Connect timeout",
45: "Error sending message",
46: "Server response timeout",
47: "Unspecified read error",
49: "Undefined socket error",
50: "Invalid login information",
57: "Invalid API version",
51: "Contact attempts cannot exceed 99",
52: "Contact cycle delay cannot exceed 9999",
53: "Text device delay too large",
54: "Invalid notification ID",
55: "Invalid notification title",
56: "No device or no text specified"
}
exports.post = function(req, res) {
if(!('notification' in req.body)) {
res.send({status: 'error', error: "notification parameter missing"});
return;
}
if(req.body.notification == '') {
res.send({status: 'error', error: "notification parameter is empty"});
return;
}
if(!('message' in req.body)) {
res.send({status: 'error', error: "message parameter missing"});
return;
}
if(req.body.message == '') {
res.send({status: 'error', error: "notification parameter is empty"});
return;
}
var cmd = '/usr/local/bin/inConsole -I -i "' + req.body.notification + '" -X "' + req.body.message + '"';
log.write_to_log("REQUEST");
log.write_to_log(req.body);
console.log("command: " + cmd)
exec(cmd, function(err, stdout, stderr) {
console.log('exec command')
var status = {};
if(err) {
if(err.code in errorCodes) {
status = {status: 'error', errorCode: err.code, errorText: errorCodes[err.code]};
} else {
status = {status: 'error', errorCode: err.code, errorText: "Unknown error occured"};
}
} else {
var response = stdout.replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm,"").split('\n');
status = {status: 'successful', reportId: response[response.length - 1] };
}
log.write_to_log("RESPONSE");
log.write_to_log(status);
res.send(status);
})
}
不知道为什么这不起作用..