Node.js http serve folder content

Description

Node.js http serve folder content


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

console.log("\nStarting node.js server...\n");

var config = JSON.parse(fs.readFileSync("config.json"));
var host = config.host;
var port = config.port;
var server = http.createServer(function(request, response){
  console.log("Received request: " + request.url + "\n");
  fs.readFile("./public" + request.url, function(error, data){
    if(error){//from w  w w.j  ava2s  .  c om
      response.writeHead(404, {"Content-type":"text/plain"});
      response.end("Page Not Found!");
    } else{
      response.writeHead(200, {"Content-type":"text/html"});
      response.end(data);
    }

  });

});

server.listen(port, host, function(){
  console.log("Listening " + host + ":" + port);
});



PreviousNext

Related