Making Code Stick: Day 6

Getting near the end here, just three lessons left.

Lesson 11: HTTP FileServer

Obviously, we could have read the file into memory, converted it to a string, and passed it back out, but with the fs.createReadStream() method, we can just pipe the incoming stream to the outgoing stream and avoid all the intermediate messiness.

The interesting part is that my code passed despite missing an important line.

Between lines 7 and 8 of the code sample above, the demo sample did something I forgot to do (and something they didn’t check for)…

res.writeHead(200, { 'content-type': 'text/plain' })

They set the response header first. Coming from the web/browser world, I’d think I’d have remembered that, but I didn’t even think about response headers. And this is an important thing to remember. Even if headers weren’t checked for here, a number of libraries look for the response code to determine how they should handle the data coming back. If you send a response code of 200, they know everything is all right, but if it’s 404, then they know there’s a problem. It’s important to send response codes when sending HTTP responses.

Lesson 12: HTTP UpperCaserer

This one has you install the through2-map library.

Two things I noticed. One, they didn’t send a header this time. It doesn’t matter to the final result of the exercise if you do, but the inconsistency bothered me.

Two, I was curious about what the piping through the through2-map module was replacing, so I rewrote a simplified version of the solution that also generated output that worked.

Basically, req is implementing the Stream.readable() class, plus some goodness added by the http module. If you’d rather collect the incoming data into a single string than pipe the stream through a conversion function and right back out, you have that option. You probably wouldn’t want to… but you could.

Leave a Reply

Your email address will not be published. Required fields are marked *

*