Wednesday 26 April 2017

Node.js - piping a readable stream to http response

I am doing node.js exercises from nodeschool.io (learnyounode). One of the exercises involves creating a http server which serves a text file from a readable file stream. I'm very new to asynchronous programming. The solution I came up with is:

var http = require('http');
var fs = require('fs');

var readable = fs.createReadStream(process.argv[3]);
var server = http.createServer(function(request, response) {
    readable.on('data', function(chunk) {
      response.write(chunk);
    })
});

server.listen(process.argv[2]);

This works, however the official solution uses a pipe instead of on-data event:

var http = require('http')
var fs = require('fs')

var server = http.createServer(function (req, res) {
  res.writeHead(200, { 'content-type': 'text/plain' })
  fs.createReadStream(process.argv[3]).pipe(res);
})

server.listen(Number(process.argv[2]))

What are the (potential) differences and/or benefits of doing it either way?



via Marcin Wasilewski

No comments:

Post a Comment