Simple Web Server in NodeJs

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In the previous tutorial, we learned to write a basic nodejs app that only printed some text to the screen — call it an “Hello World” app if you like — just to test that nodejs is working.

But nodejs is typically run as a web server processing http requests.  We will show you how to do a simple web server in this tutorial.

1. In a node.js project directory which we will call “simplewebserver”, write the following into a file called “server.js”.

nodejs simple web server

nodejs simple web server

2.  require(“http”) tells node that we will be using one of its built-in library.  In our case, we will be using its “http” library.  We store an instance of this library in the http javascript variable.

3. The http library has a function createServer() which as its name imply creates an http server, which we then store that instance of the server into the server Javascript variable like so…

var server = http.createServer();

4.  The function createServer actually requires a function as an argument.  This function takes two parameters: a request and a response.  Inside this function we write code that tells nodejs what to do with requests that are coming in and what to output as response.

var server = http.createServer(function(request,response) {
 response.writeHead(200, {'Content-Type': 'text/plain' });
 response.write("Some HTML here");

The response.write() write out some HTML.  The response.end() must always be included and it also can write out some HTML.  Or can be used just to end the writing.  The response.writeHead writes the response header with status code 200 (meaning “OK”).   The call to writeHead can be omitted because the nodejs guide says …

“If you call response.write() or response.end() before calling this, the implicit/mutable headers will be calculated and call this function for you.”

5.  That tells nodejs what to output, but we still need to tell it to start listening to requests.   We choose for it to listen on port 3000 (only because that is the default port that expressjs listens on).

console.log("server listening on port 3000...");

By the way, this tutorial is just for learning.  On a production environment, we would typically use expressjs with nodejs and not be writing this type of code.

6.  Run the server at your nodejs command window with …

node server.js

You should get back in the console …

“server listening on port 3000…”

7.  Bring up a web browser pointing to “http://localhost:3000/” and you should see “Some HTML here” as output.

8.  Do Ctrl-C in nodejs console to terminate the server.