javascript - 我只能捕获 Node.js 脚本的第一行输出

标签 javascript php windows node.js

我为 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/

相关文章:

php - 将数组数据插入数据库时​​出现问题

php - 取消链接功能不适用于 Internet Explorer 中的图像

windows - 我可以在 Linux 上生成带有原生 Excel 图表的 Excel 文件吗?

c# - 将项目添加到 ListView 时,MultiDataTrigger 的 EnterActions 中的 ColorAnimation 不触发

windows - 为什么需要 IP_MULTICAST_IF 和 IPV6_MULTICAST_IF?

javascript - 将随机 background.color 分配给具有随机 ID 的对象

javascript - Mongoose - 使用嵌套模型更新插入文档

javascript - 重新加载 iframe 时捕获 javascript 事件

javascript - Jquery在javascript中访问iframe文档内容

PHP:如果我允许用​​户将内容添加到双引号变量中,这是否会被操纵为漏洞?