The goal of this exercise is to create an HTTP server that serves the same text file for each request that it receives. Here is my code. It doesn't work.
var http = require ('http');
var fs = require ('fs');
var port = process.argv[2];
var file = process.argv[3];
var bl = require ('bl');
var server = http.createServer(function (request, response) {
var stream = fs.createReadStream(file);
var streamPipe = stream.pipe(response);
response.write(streamPipe);
});
server.listen(port);
I checked the correct answer, and that is to place the following code at the first line of the function, and remove my response.write() method:
response.writeHead(200, { 'content-type': 'text/plain' });
instead of my code, which I thought would write the data piped from the request stream to the response stream (line 10):
response.write(streamPipe)
I don't understand. Shouldn't response.writeHead go after the stream is established using the .createReadStream method, and not before?
Aren't I sending already existing data with response.write()? I want this to return a string and not an object, but the parameter has to be a string first, otherwise it doesn't work. The toString() method returns [object Object].
Can someone please explain the parameters of the writeHead method, and why it goes before everything else?
I realize this is a loaded question. I'm new to node, really excited to learn, but I just find it so difficult to understand. I have pretty basic JavaScript experience, and some Java, so I appreciate any and all help for an aspiring node.js developer.