var http = require('http');
var fs = require('fs');
var path = process.argv[2];
var str="";
function onRequest(request, response) {
str += "";
console.log("Request received" + path);
fs.readdir(path, function(err, items) {
str += items;
});
response.writeHead(200, {"Context-Type": "text/plain"});
response.write(new Buffer(str).toString());
response.end();
}
http.createServer(onRequest).listen(8000);
The above snippet creates a http server which gets a directory path from the user as argument. Make a http request to get the list of files available in the directory and send them back as a response.
The response is written to the page only on the second request. The page is shown empty on the first request.
Could anyone help. Thanks in advance!!
Javascript is non blocking, so
will be executed before
With
it will send the response after
readdir
.And in Javascript the program will not be started for every new Request (like in PHP). So your global variable will be shared between all requests. If you don't want that put the
var str="";
inonRequest
.If you have multiple routes you also want to look into something like express, because the
http
module doesn't include routing.