-2
var http = require("http");
var fs = require("fs");

http.createServer(function(request, response) {
    console.log("User request received");
    response.writeHead(200, {"Content-Type": "Text/plain"});
    fs.createReadStream(process.argv[3]).pipe(response);
    response.end();
}).listen(process.argv[2]);

console.log("Server is running...");

This program takes the port number and the file path as command line parameters.
When I run it in node, even though I pass the correct command line arguments, the file is not served when accessed from the browser

I don't know where the error is occurring

1 Answers1

1

This might not be the best answer but it looks like the call to response.end() is closing the stream before the file is served. Following the logic on this answer:

createReadStream().pipe() Callback

You need a callback on when the stream closes, so I found this works but again, I don't know if this is the most elegant solution:

var http = require("http");
var fs = require("fs");

http.createServer(function(request, response) {
console.log("User request received");
response.writeHead(200, {"Content-Type": "Text/plain"});
var t = fs.createReadStream(process.argv[3]).pipe(response);

t.on('close', function(){
    response.end();
});

}).listen(process.argv[2]);
Community
  • 1
  • 1
Sweet_Pete
  • 403
  • 4
  • 10