rolfen
3/8/2016 - 12:26 AM

Quick node HTTP server

Quick node HTTP server

A quick and small HTTP server in node, for development.
Just paste into index.js, and then run node index.js.
This will only serve index.html (can be changed in the code), which is often enough.

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

var localIP = "127.0.0.1";
var port = 8080; 
var indexFile = './index.html';


var process = function(req, res) {
    fs.readFile(indexFile, function(err, data) {
        if(!err) {
            console.log("Served " + indexFile);
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.write(data);
            res.end();    
        } else {
            console.dir(err);
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end("Error");
        }
    });
}

var server = http.createServer(process);
server.listen(port, localIP);

console.log('Server running at http://'+ localIP +':'+ port +'/');