在 Node.js 网络中使用 pipe() [英] Using pipe() in Node.js net
问题描述
我无法理解 pipe 函数>net 模块.
var net = require('net');var server = net.createServer(函数(套接字){socket.write('回声服务器
');socket.pipe(socket);});
谁能解释一下这是如何工作的以及为什么需要它?
pipe()
函数从可读流中读取可用数据并将其写入目标可写流.>
文档中的示例是一个回显服务器,它是一个发送它接收到的内容的服务器.socket
对象实现了可读和可写的流接口,因此它将接收到的任何数据写回套接字.
这与使用事件侦听器的 pipe()
方法等效:
var net = require('net');net.createServer(函数(套接字){socket.write('回声服务器
');socket.on('数据',函数(块){socket.write(块);});socket.on('end', socket.end);});
I'm having trouble wrapping my head around the pipe
function shown in several Node.js examples for the net module.
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('Echo server
');
socket.pipe(socket);
});
Can anyone offer an explanation on how this works and why it's required?
The pipe()
function reads data from a readable stream as it becomes available and writes it to a destination writable stream.
The example in the documentation is an echo server, which is a server that sends what it receives. The socket
object implements both the readable and writable stream interface, so it is therefore writing any data it receives back to the socket.
This is the equivalent of using the pipe()
method using event listeners:
var net = require('net');
net.createServer(function (socket) {
socket.write('Echo server
');
socket.on('data', function(chunk) {
socket.write(chunk);
});
socket.on('end', socket.end);
});
这篇关于在 Node.js 网络中使用 pipe()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!