node.js 是否可以通过管道传输到 console.log?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24427329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:32:57  来源:igfitidea点击:

Is it possible to pipe to console.log?

node.jsstream

提问by spinners

I am trying to learn node.js.

我正在尝试学习 node.js。

I am trying to understand streams and piping.

我试图了解流和管道。

Is it possible to pipe the response of http request to console.log?

是否可以将 http 请求的响应通过管道传输到 console.log?

I know how to do this by binding a handler to the data event but I am more interested in streaming it to the console.

我知道如何通过将处理程序绑定到数据事件来做到这一点,但我对将其流式传输到控制台更感兴趣。

http.get(url, function(response) {
  response.pipe(console.log);
  response.on('end', function() {
    console.log('finished');
  });
});

回答by Ben Fortune

console.logis just a function that pipes the process stream to an output.

console.log只是一个将流程流传输到输出的函数。

Note that the following is example code

请注意,以下是示例代码

console.log = function(d) {
  process.stdout.write(d + '\n');
};

Piping to process.stdoutdoes exactly the same thing.

管道到process.stdout做的事情完全一样。

http.get(url, function(response) {
  response.pipe(process.stdout);
  response.on('end', function() {
    console.log('finished');
  });
});

Note you can also do

注意你也可以做

process.stdout.write(response);