Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

136
Views
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?

8 months ago · Santiago Trujillo
1 answers
Answer question

0

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 e.g. 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).

8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs