[英]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.