(LearnYouNode) HTTP-UpperCaser Solution Explanation, please!

(LearnYouNode) HTTP-UpperCaser Solution Explanation, please!
0.0 0

#1

I just completed the learnyounode ‘http-uppercaser’ challenge. I couldn’t figure out why the .toUpperCase() method wasn’t capitalizing the chunk being returned. I still don’t understand what the difference is between the code I wrote and the ‘solution’ code. Can someone explain this difference and what’s happening under the hood?

My initial code that failed:

var fs = require('fs');
var http = require('http');
var port = process.argv[2];

// npm package that you can use to 
// tranform stream data as it's passed through.
var map = require('through2-map');

var server = http.createServer(function(request, response) {
    request.pipe(map(function(chunk) {
        return chunk.toString().toUpperCase();
    }));
request.pipe(response);
});

server.listen(port);

The ‘correct’ solution:

var fs = require('fs');
var http = require('http');
var port = process.argv[2];

// npm package that you can use to 
// tranform stream data as it's passed through.
var map = require('through2-map');

var server = http.createServer(function(request, response) {
    request.pipe(map(function(chunk) {
        return chunk.toString().toUpperCase();
    })).pipe(response);
});

server.listen(port);

Thanks!


#2

In your solution, you assume that .pipe() mutated request with the new (uppercased) data which is wrong. According to the docs .pipe() returns a reference to the destination (the parameter you pass to it) which holds the updated data and allows you to pass it down the chain. It doesn’t change your readable stream (request in your case)


#3

ahh ok, thanks so much for the explanation & link!