Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pipe() in Node.js 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?

like image 729
Nick Parsons Avatar asked Nov 20 '13 01:11

Nick Parsons


People also ask

What is the use of pipe in node JS?

pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable.

What is buffer class in node JS?

The Buffer class in Node. js is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data.

Can I use JavaScript in node JS?

Node. js allows you to run JavaScript on the server.

What is Node JS stream?

Streams are one of the fundamental concepts that power Node. js applications. They are data-handling method and are used to read or write input into output sequentially. Streams are a way to handle reading/writing files, network communications, or any kind of end-to-end information exchange in an efficient way.


4 Answers

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);
});
like image 175
hexacyanide Avatar answered Oct 27 '22 18:10

hexacyanide


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.

like image 20
user949300 Avatar answered Oct 27 '22 18:10

user949300


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.

like image 3
CK5 Avatar answered Oct 27 '22 19:10

CK5


Consider the following request handler

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.

like image 2
Harrison Kamau Avatar answered Oct 27 '22 19:10

Harrison Kamau