• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

243
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?

over 3 years 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).

over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error