简体   繁体   English

节点脚本到 console.log 并返回数据

[英]Node Script to console.log and return data

Here is a dummy script:这是一个虚拟脚本:

console.log('hello');
process.stdout.write(JSON.stringify({ foo: 'bar' }));

If I were to run node index.js | jq.如果我要运行node index.js | jq. node index.js | jq. this would cause a parse error because of the console.log .由于console.log这将导致parse error Is it possible to have a Node script that does console logs to the terminal, but then the data that is to be returned from the script (that can then be piped to other scripts) is separate?是否可以有一个节点脚本将控制台日志记录到终端,但是从脚本返回的数据(然后可以通过管道传输到其他脚本)是分开的? I want in the example above, {foo: 'bar'} to be piped only to jq but I still want to see the hello logged to terminal.我希望在上面的示例中, {foo: 'bar'}仅通过管道传输到jq但我仍然希望看到hello记录到终端。

According to NodeJS docs , the console.log() outputs to stdout (used as input by the piped jq command).根据NodeJS 文档console.log()输出到stdout (用作管道jq命令的输入)。

You can replace the console.log call by console.error since it outputs to stderr instead, and will not be read by the jq command.您可以用console.error替换console.log调用,因为它输出到stderr ,并且不会被jq命令读取。 (unless you redirect stderr to stdout) (除非您将标准错误重定向到标准输出)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM