我为 Node.js 编写了一个简单的测试脚本:
console.log("Line #1 stdout");
console.log("Line #2 stdout");
console.log("Line #3 stdout");
console.error("Line #1 stderr");
console.error("Line #2 stderr");
console.error("Line #3 stderr");
process.exit(33);
我需要从 PHP 脚本捕获其完整输出,但是无论我如何尝试,我都只获得每个流的第一行:
var_dump(`node test.js 2>&1`);
exec('node test.js 2>&1', $output);
var_dump($output);
$descriptorspec = array(
1 => array('pipe', 'w'), // stdout
2 => array('pipe', 'w'), // stderr
);
$process = proc_open('node test.js', $descriptorspec, $pipes);
var_dump(stream_get_contents($pipes[1]));
var_dump(stream_get_contents($pipes[2]));
proc_close($process);
string(30) "Line #1 stdout
Line #1 stderr
"
array(2) {
[0]=>
string(14) "Line #1 stdout"
[1]=>
string(14) "Line #1 stderr"
}
string(15) "Line #1 stdout
"
string(15) "Line #1 stderr
"
我是否遗漏了有关 console
对象的一些基本概念?
编辑:这并不是严格意义上的 PHP 问题;而是一个问题。同样的情况也发生在命令行中:
C:\test>node test.js 2>&1 | sort /r
Line #1 stdout
Line #1 stderr
这一定是 Node.js 的特殊性,我还没有解决。
最佳答案
这显然是 Node.js 中的一个已知问题。甚至还有a package to fix it :
exit
A replacement for process.exit that ensures stdio are fully drained before exiting.
To make a long story short, if process.exit is called on Windows, script output is often truncated when pipe-redirecting stdout or stderr. This module attempts to work around this issue by waiting until those streams have been completely drained before actually calling process.exit.
See Node.js issue #3584 for further reference.
使用这样的包,替换它:
process.exit(33);
...这样:
var exit = require('exit');
exit(33);
...产生预期的行为:控制台输出在进程结束之前刷新。
关于javascript - 我只能捕获 Node.js 脚本的第一行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945559/