[英]spawn a child process in node.js, data is undefined
这里我试图执行一个exe file
。 通过命令行执行它正常工作并打印我想要的数据。 但是使用node.js它会将数据打印为undefined
。 这是我正在使用的代码
var server = http.createServer(function (req, res) {
switch (req.url) {
case '/start':
console.log("begin...............");
req.on("data", function (value) {
exec('CALL hello.exe', function(err, data) {
console.log(err)
console.log(data.toString());
});
});
req.on("end", function () {
console.log(data); // prints undefined
console.log(JSON.stringify(data));
console.log("hello");
console.log("before--------------");
res.writeHead(200);
res.end(data);
});
break;
}
});
server.listen(8080);
console.log("Server running on the port 8080");
只需像下面那样运行exec
调用。
var http = require('http');
var exec = require('child_process').exec;
var server = http.createServer(function (req, res) {
switch (req.url) {
case '/start':
console.log("begin...............");
exec('CALL hello.exe', function(err, data) {
console.log(err);
console.log(data);
console.log(data); // prints undefined
console.log(JSON.stringify(data));
console.log("hello");
console.log("before--------------");
res.writeHead(200);
res.end(data);
});
break;
}
});
server.listen(8080);
console.log("Server running on the port 8080");
在req
上收听data
事件会将其切换为流/流模式
试试这样吧。
我想这会对你有所帮助。
var http = require('http');
var exec = require('child_process').execFile;
var server = http.createServer(function (req, res) {
switch (req.url) {
case '/start':
console.log("begin...............");
exec('hello.exe', function(err, data) {
console.log(err);
console.log(data);
console.log(data); // prints undefined
console.log(JSON.stringify(data));
console.log("hello");
console.log("before--------------");
res.writeHead(200);
res.end(data);
});
break;
}
});
server.listen(8080);
console.log("Server running on the port 8080")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.