简体   繁体   中英

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?

Well, there's more code in your version, and that usually means you have more options to make mistakes. Take into account some edge cases, like what happens when the stream throws an error?

I'm not exactly sure what the behavior would be (you can check yourself by eg inserting some non-existing filename) but chances are that in your version the error handling is not working very well, potentially ignoring errors (because you're not listening for error events).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM