Node.js a simple webserver

Some years back I started to tease my colleagues that they should be running on the server instead of .net. They laughed, but when Google first launched a based server they may have been thinking more seriously about what I suggested them.

This blog post will not take you through installing NodeJS. Visit

NodeJS here there and everywhere

Today I am happy to be able to be able to play around with javascript based web servers on my Mac.

It is also used by my editor (Sublime Text – SBT) to extend its functionality – like JSHint, which is done using NodeJS from within SBT.

Though I have not yet found the perfect place to get easy hosting for NodeJS apps, I am in no doubt that we have only seen the start of a new area.

It makes sense to learn javascript and use it not only in a browser, but also in NodeJS as for instance a web server or on your OS as a great application platform.

A simple web server

Guess that lots of simple 15 lines of javascript – so I must also have mine! :–)

Here goes, it is much copy and paste – but still…

Respond with the request as

You need two files:

The server.js which is the web server:

// server.js
var http = require("http");
var JSON2 = require("JSON2"); // npm install JSON2

function start() {
  function onRequest(request, response) {
    console.log("Request received ");
    response.writeHead(200, {"Content-Type": "application/json"});
    response.write("{\"request\":"+JSON2.stringify(JSON2.decycle(request))+"}");
    response.end();
  }
  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}
exports.start = start;

The application uses a Node Package, which you need to install before running the app.

With NodeJS it is very easy – you simply open a Terminal (OSX);

npm install JSON2

You can find Node Packages here: https://www.npmjs.org/

Also on https://nodejsmodules.org/ you can find many NodeJS Packages.

And the index.js which you use to start your server:

// index.js
var server = require("./server");
server.start();

Save the files in a folder where you can run node.js.

Running the web server

On OSX (Mac) you simply open a terminal at the folder where you saved the files.

To start the server you type:

node index.js

The app will write to the terminal window that is has started.

To visit the web server visit the page: http://localhost:8888 or http://127.0.0.1:8888

The response will be a JSON text object with a serialized version of the Request object.

It is in other words what the web server can see from your request for a page.

Mine looked like this:

{
    "request": {
        "_readableState": {
            "highWaterMark": 16384,
            "buffer": [],
            "length": 0,
            "pipes": null,
            "pipesCount": 0,
            "flowing": false,
            "ended": false,
            "endEmitted": false,
            "reading": false,
            "calledRead": false,
            "sync": true,
            "needReadable": false,
            "emittedReadable": false,
            "readableListening": false,
            "objectMode": false,
            "defaultEncoding": "utf8",
            "ranOut": false,
            "awaitDrain": 0,
            "readingMore": false,
            "decoder": null,
            "encoding": null
        },
        "readable": true,
        "domain": null,
        "_events": {},
        "_maxListeners": 10,
        "socket": {
            "_connecting": false,
            "_handle": {
                "fd": 13,
                "writeQueueSize": 0,
                "owner": {
                    "$ref": "$[\"socket\"]"
                },
                "reading": true
            },
            "_readableState": {
                "highWaterMark": 16384,
                "buffer": [],
                "length": 0,
                "pipes": null,
                "pipesCount": 0,
                "flowing": false,
                "ended": false,
                "endEmitted": false,
                "reading": true,
                "calledRead": true,
                "sync": false,
                "needReadable": true,
                "emittedReadable": false,
                "readableListening": false,
                "objectMode": false,
                "defaultEncoding": "utf8",
                "ranOut": false,
                "awaitDrain": 0,
                "readingMore": false,
                "decoder": null,
                "encoding": null
            },
            "readable": true,
            "domain": null,
            "_events": {
                "drain": [null, null],
                "close": [null, null]
            },
            "_maxListeners": 10,
            "_writableState": {
                "highWaterMark": 16384,
                "objectMode": false,
                "needDrain": false,
                "ending": false,
                "ended": false,
                "finished": false,
                "decodeStrings": false,
                "defaultEncoding": "utf8",
                "length": 0,
                "writing": false,
                "sync": true,
                "bufferProcessing": false,
                "writecb": null,
                "writelen": 0,
                "buffer": [],
                "errorEmitted": false
            },
            "writable": true,
            "allowHalfOpen": true,
            "destroyed": false,
            "bytesRead": 403,
            "_bytesDispatched": 0,
            "_pendingData": null,
            "_pendingEncoding": "",
            "server": {
                "domain": null,
                "_events": {},
                "_maxListeners": 10,
                "_connections": 2,
                "connections": 2,
                "_handle": {
                    "fd": 12,
                    "writeQueueSize": 0,
                    "owner": {
                        "$ref": "$[\"socket\"][\"server\"]"
                    }
                },
                "_usingSlaves": false,
                "_slaves": [],
                "allowHalfOpen": true,
                "httpAllowHalfOpen": false,
                "timeout": 120000,
                "_connectionKey": "4:0.0.0.0:8888"
            },
            "_idleTimeout": 120000,
            "_idleNext": {
                "_connecting": false,
                "_handle": {
                    "fd": 14,
                    "writeQueueSize": 0,
                    "owner": {
                        "$ref": "$[\"socket\"][\"_idleNext\"]"
                    },
                    "reading": true
                },
                "_readableState": {
                    "highWaterMark": 16384,
                    "buffer": [],
                    "length": 0,
                    "pipes": null,
                    "pipesCount": 0,
                    "flowing": false,
                    "ended": false,
                    "endEmitted": false,
                    "reading": true,
                    "calledRead": true,
                    "sync": false,
                    "needReadable": true,
                    "emittedReadable": false,
                    "readableListening": false,
                    "objectMode": false,
                    "defaultEncoding": "utf8",
                    "ranOut": false,
                    "awaitDrain": 0,
                    "readingMore": false,
                    "decoder": null,
                    "encoding": null
                },
                "readable": true,
                "domain": null,
                "_events": {
                    "drain": [null, null]
                },
                "_maxListeners": 10,
                "_writableState": {
                    "highWaterMark": 16384,
                    "objectMode": false,
                    "needDrain": false,
                    "ending": false,
                    "ended": false,
                    "finished": false,
                    "decodeStrings": false,
                    "defaultEncoding": "utf8",
                    "length": 0,
                    "writing": false,
                    "sync": true,
                    "bufferProcessing": false,
                    "writecb": null,
                    "writelen": 0,
                    "buffer": [],
                    "errorEmitted": false
                },
                "writable": true,
                "allowHalfOpen": true,
                "destroyed": false,
                "bytesRead": 0,
                "_bytesDispatched": 0,
                "_pendingData": null,
                "_pendingEncoding": "",
                "server": {
                    "$ref": "$[\"socket\"][\"server\"]"
                },
                "_idleTimeout": 120000,
                "_idlePrev": {
                    "$ref": "$[\"socket\"]"
                },
                "_idleStart": 1396077839816,
                "parser": {
                    "_headers": [],
                    "_url": "",
                    "socket": {
                        "$ref": "$[\"socket\"][\"_idleNext\"]"
                    },
                    "incoming": null,
                    "maxHeaderPairs": 2000
                },
                "_paused": false
            },
            "_idlePrev": {
                "_idleNext": {
                    "$ref": "$[\"socket\"]"
                }
            },
            "_idleStart": 1396077839816,
            "parser": {
                "_headers": [],
                "_url": "",
                "socket": {
                    "$ref": "$[\"socket\"]"
                },
                "incoming": {
                    "$ref": "$"
                },
                "maxHeaderPairs": 2000
            },
            "_paused": false,
            "_httpMessage": {
                "domain": null,
                "_events": {},
                "_maxListeners": 10,
                "output": [],
                "outputEncodings": [],
                "writable": true,
                "_last": false,
                "chunkedEncoding": true,
                "shouldKeepAlive": true,
                "useChunkedEncodingByDefault": true,
                "sendDate": true,
                "_headerSent": false,
                "_header": "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nDate: Sat, 29 Mar 2014 07:23:59 GMT\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\n",
                "_hasBody": true,
                "_trailer": "",
                "finished": false,
                "_hangupClose": false,
                "socket": {
                    "$ref": "$[\"socket\"]"
                },
                "connection": {
                    "$ref": "$[\"socket\"]"
                },
                "statusCode": 200
            }
        },
        "connection": {
            "$ref": "$[\"socket\"]"
        },
        "httpVersion": "1.1",
        "complete": false,
        "headers": {
            "host": "localhost:8888",
            "connection": "keep-alive",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36",
            "accept-encoding": "gzip,deflate,sdch",
            "accept-language": "en-US,en;q=0.8,da;q=0.6"
        },
        "trailers": {},
        "_pendings": [],
        "_pendingIndex": 0,
        "url": "/",
        "method": "GET",
        "statusCode": null,
        "client": {
            "$ref": "$[\"socket\"]"
        },
        "_consuming": false,
        "_dumped": false,
        "httpVersionMajor": 1,
        "httpVersionMinor": 1,
        "upgrade": false
    }
}
US

Leave a Reply