A Simple Web Server in NodeJS

If you haven't already set up your Node sample project, you can quickly do so by following these instructions

You can use NodeJS to create various types of server applications, and the next code sample shows demonstrates a very simple web server application.

Create a file named simple-web-server.js in your samples folder and put this code in it:

const http = require('http');

const app = http.createServer((req, res)=>{
    console.log("handling request on server.....");
    res.end("Hello World!");
});

app.listen(8080);
console.log("Listening for requests on port 8080");

We'll go over the code in a minute, but first run this node script to start the web server (run this command from the project folder):

node samples/simple-web-server.js

The terminal should tell you that your app is 'Listening for requests on port 8080'. And if you open a browser and go to localhost:8080, you should see a simple web page that says 'Hello World!'.

Now for some notes on the code in this little application:

  1. The first line uses the require() function to import the http module, which is another module that comes with NodeJS (and it's used to handle HTTP requests and send HTTP responses).
  2. Then the createServer() method of the http module (which is an object) is invoked. The paramater passed in is a callback function that will be executed whenever the app receives an HTTP request. The createServer() method returns an object that represents our web server application.
  3. When NodeJS invokes your callback, it will pass in two parameters, the first is an object represents the incoming HTTP request, and the second is an object that represents the HTTP response. We could explore these objects by console logging them - they are both packed with quite a few properties and methods.
  4. Inside the body of the callback function, we do a console log, which will appear in the terminal each time a request comes to the server. And then we call the write() method of the response object. This will send the text 'Hello World!' to the browser that made the request.
  5. Finally, we call the listen() method on our application object, which starts the web server and instructs it to listen for HTTP requests on port 8080.