Node.js child.spawn stdout "live" 每行
Node.js child.spawn stdout "live" at every line
我打算在 Node.js
中使用 Perl 脚本的输出
for (my $i=10;$i<100 ;$i+=30 )
{
printf "$i\n";
sleep(1);
}
此脚本由 child_process.spawn 方法调用。
我的问题是,我需要处理每一个输出。有没有办法在 perl 向 stdout 发送新行时立即开始事件?在我的实际代码中,我可以在 perl 脚本完成后看到批量输出 运行 并且无法使用单行
function setStuff() {
var command = "perl";
var scriptpath = "script.pl";
var arg = [scriptpath];
run(command, arg);
}
function run(cmd, arg) {
var spawn = require('child_process').spawn;
var command = spawn(cmd, arg, {detached: true, stdout: 'pipe'});
command.unref();
var lineBuffer = "";
command.stdout.pipe(process.stdout);
command.stdout.on('data', function (data) {
lineBuffer += data.toString();
var lines = lineBuffer.split("\n");
for (var i = 0; i < lines.length - 1; i++) {
var line = lines[i];
console.log(line);
}
});
}
将此放在您的 perl 文件中以禁用输出缓冲:
select(STDOUT); $| =1;
您还需要修复 on 'data' 处理程序,以便您在使用数据时不会管理 lineBuffer 变量。要修复它:
command.stdout.on('data', function (data) {
var lines = (lineBuffer + data).split("\n");
if(data[data.length-1] != '\n') {
lineBuffer = lines.pop();
}else{
lineBuffer = '';
}
for (var i = 0; i < lines.length - 1; i++) {
var line = lines[i];
console.log(line);
}
});
还有,是不是少了一个stdout.setEncoding('utf8');
?
我打算在 Node.js
中使用 Perl 脚本的输出for (my $i=10;$i<100 ;$i+=30 )
{
printf "$i\n";
sleep(1);
}
此脚本由 child_process.spawn 方法调用。 我的问题是,我需要处理每一个输出。有没有办法在 perl 向 stdout 发送新行时立即开始事件?在我的实际代码中,我可以在 perl 脚本完成后看到批量输出 运行 并且无法使用单行
function setStuff() {
var command = "perl";
var scriptpath = "script.pl";
var arg = [scriptpath];
run(command, arg);
}
function run(cmd, arg) {
var spawn = require('child_process').spawn;
var command = spawn(cmd, arg, {detached: true, stdout: 'pipe'});
command.unref();
var lineBuffer = "";
command.stdout.pipe(process.stdout);
command.stdout.on('data', function (data) {
lineBuffer += data.toString();
var lines = lineBuffer.split("\n");
for (var i = 0; i < lines.length - 1; i++) {
var line = lines[i];
console.log(line);
}
});
}
将此放在您的 perl 文件中以禁用输出缓冲:
select(STDOUT); $| =1;
您还需要修复 on 'data' 处理程序,以便您在使用数据时不会管理 lineBuffer 变量。要修复它:
command.stdout.on('data', function (data) {
var lines = (lineBuffer + data).split("\n");
if(data[data.length-1] != '\n') {
lineBuffer = lines.pop();
}else{
lineBuffer = '';
}
for (var i = 0; i < lines.length - 1; i++) {
var line = lines[i];
console.log(line);
}
});
还有,是不是少了一个stdout.setEncoding('utf8');
?