在Node.js net中使用pipe() [英] Using pipe() in Node.js net

查看:132
本文介绍了在Node.js net中使用pipe()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法绕着 pipe 函数包裹我的脑袋。 api / net.html> net 模块。

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\r\n');
  socket.pipe(socket);
});

有人可以解释这是如何工作的以及为什么需要它?

Can anyone offer an explanation on how this works and why it's required?

推荐答案

pipe()函数在可读流中读取数据并将其写入目标可写流。

The pipe() function reads data from a readable stream as it becomes available and writes it to a destination writable stream.

文档中的示例是一个echo服务器,它是一个发送它接收内容的服务器。 套接字对象实现了可读和可写的流接口,因此它将收到的任何数据写回套接字。

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.

这相当于使用事件监听器使用 pipe()方法:

This is the equivalent of using the pipe() method using event listeners:

var net = require('net');
net.createServer(function (socket) {
  socket.write('Echo server\r\n');
  socket.on('data', function(chunk) {
    socket.write(chunk);
  });
  socket.on('end', socket.end);
});

这篇关于在Node.js net中使用pipe()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆