添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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\r\n');
  socket.on('data', function(chunk) {
    socket.write(chunk);
  socket.on('end', socket.end);
                It's located here. Then, if you take a look here, it's stated that net.Socket instances implement a duplex stream.
– hexacyanide
                Jul 11, 2014 at 17:46
                but what "implement ad duplex stream interface" mean ? Does it mean that it inherits from it? Stream is in net.Socket prototype ?  Why is it called "interface" when interface to me is just "document" that specify what methods could you find in some object..
– Paweł Brewczynski
                Jul 11, 2014 at 17:51
                Yes, it means it inherits from stream.Duplex, which inherits both stream.Readable and stream.Writable. In this context, "interface" isn't strictly the OOP definition of interface, it can just be a contact point between applications.
– hexacyanide
                Jul 11, 2014 at 18:11
                What do you mean by "contact point between applications" ?   And why they use such a term that could be misleading. And they won't say how it's implemented (is this object is in prototype chain, or is it a mixin)
– Paweł Brewczynski
                Jul 11, 2014 at 18:14

pipe() reads from a readable stream and writes to a writeable stream, much like a Unix pipe. It does all "reasonable" things along the way with errors, end of files, if one side falls behind etc. Your particular example is slightly confusing because the socket is both readable and writeable.

An easier to understand example is in this SO question where you read from an http request and write to an http response.

There are 2 sockets per Server-Client Connection (2 endpoints). Socket binds IP Address:Port Number. The client gets assigned random port numbers, while the server has dedicated port number. This is the basic explanation of how socket works.

Piping is reserved for redirecting a readable stream to a writable stream.

What socket.pipe(socket) does? It redirects all the data from the readable stream (server) to the writable stream (client). We can tweak this by adding event listeners as @hexacyanide has pointed out.

var server = http.createServer(function(req, res){
     console.log('Request for ' + req.url + ' by method ' + req.method);
    if(req.method == 'GET'){
        var fileurl;
        if(req.url == '/')fileurl = '/index.html';
        else {
            fileurl = req.url;
    var filePath = path.resolve('./public'+fileurl);
    var fileExt = path.extname(filePath);
    if(fileExt == '.html'){
          fs.exists(filePath, function(exists){
        if(!exists){
          res.writeHead(404, {'Content-Type': 'text/html'});
          res.end('<h1>Error 404' + filePath + 'not found </h1>');
          //the end() method sends content of the response to the client
          //and signals to the server that the response has been sent
          //completely
          return;
        res.writeHead(200, {'Content-Type':'text/html'});
        fs.createReadStream(filePath).pipe(res);

The fs.createReadStream method reads the file in the given file path (public/index.html) and pipe() writes it to the response (res) for client's view.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.