Node和http.get中的管道功能 [英] pipe function in Node and http.get
问题描述
我正在从 nodeschool 的研讨会中学习Node.车间名称是
learningyounode,问题编号8. HTTP COLLECT .
问题是:
编写一个程序,该程序对提供给您的URL执行HTTP GET请求
作为第一个命令行参数.从服务器收集所有数据(不是
只是第一个数据"事件),然后向控制台写入两行
(标准输出).
您写的第一行应该是代表数字的整数
从服务器接收的字符数.第二行应包含
服务器发送的完整字符字符串.
我提交的答案如下.
I am learning node under workshops from nodeschool. name of workshop is
learnyounode, question number 8. HTTP COLLECT.
Question was:
Write a program that performs an HTTP GET request to a URL provided to you
as the first command-line argument. Collect all data from the server (not
just the first "data" event) and then write two lines to the console
(stdout).
The first line you write should just be an integer representing the number
of characters received from the server. The second line should contain the
complete String of characters sent by the server.
The answer i submitted was as follows.
var http = require('http');
var url = process.argv[2];
http.get(url,function(res){
var body = '';
res.on('error',function(err){
console.error(err);
})
res.on('data',function(chunk){
body+=chunk.toString();
});
res.on('end',function(){
console.log(body.length);
console.log(body);
});
});
他们提供的答案是
var http = require('http')
var bl = require('bl')
http.get(process.argv[2], function (response) {
response.pipe(bl(function (err, data) {
if (err)
return console.error(err)
data = data.toString()
console.log(data.length)
console.log(data)
}))
})
我想知道这两个代码之间的区别.
并请说明http.get()和管道的工作方式...
I would like to know the difference between these two codes.
and please explain how http.get() and pipe works ...
推荐答案
唯一的区别是你们两个如何处理响应.您逐块处理了响应,并将等效于body
的字符串附加到了字符串之后.他们使用pipe
发送可读流response
并将其发送到可写流bl
(缓冲区列表),该流可以等待直到可读流完成后再继续.当您订阅数据"的发射器来处理响应块时,bl
会在后台进行.
The only difference is how you two handled the response. You handled the response chunk by chunk and appended the string equivalent to body
. They used pipe
to send a readable stream response
and send it to a writable stream bl
(buffer list) which can wait until the readable stream is done before proceeding. While you subscribed to the emitter of 'data' to handle the response chunks, bl
does that under the covers.
pipe
是在可读流上调用的函数,该函数传递了可写流的参数.
pipe
is a function called on a readable stream that is passed a parameter of a writable stream.
我刚刚注意到您的帖子日期.奇怪的是没有人回答...
I just noticed the date of your post. It's odd no one answered this...
这篇关于Node和http.get中的管道功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!