Creating a Node.js web server in less than ten lines of code

Node.js is a solid resource for front-end tooling. In fact, it is not uncommon for a developer to first learn about Node.js in this context. Grunt, Gulp and Bower have contributed to the popularity of this front-end build ecosystem. This article provides an introduction to one of other strengths of Node.js: acting as a web server.

I do not think any organization would base their enterprise on a Node.js web server that features ten lines of code. That said, the goal of this article is to emphasize that the steps needed to get a Node.js web server working are simple. First we will get a web server running in less than ten lines of code. And then we will expand that code so that it is easier to understand and walk-through.

To get started, clone the following git hub repository.

https://github.com/kevinchisholm/node-js-web-server-in-less-than-ten-lines-of-code.

Instructions on how to run the code are available in the Git hub page.

Example # 1:



require('http').createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Your node.js server works...in less than ten lines of code.');
}).listen(3000);
console.log('In your browser, go to: http://localhost:3000');


In example # 1, we have our Node web server. In order start up this server, run this code in your terminal: node example-1.js.

Functionality is a bit limited here. If you browse to http://localhost:3000/, you will see the text: “Your node.js server works...in less than ten lines of code".

This is probably not a candidate for the next Facebook, but we do have a working web-server in less than ten lines of code!

Example # 2:




//set a reference to the http module
var http = require('http');

//call the http module's createServer method, to create a server instance
var server = http.createServer(function (req, res) {
    //access the response object, and create a Content-Type header
    res.writeHead(200, {'Content-Type': 'text/html'});

    //end the response, sending some text (the user will see this in their browser)
     res.end('Your node.js server works...in a little more than lines of code.');
})

//tell the server to listen for requests
server.listen(3000);

//just lets us know that the server is running
console.log('In your browser, go to: http://localhost:3000');

In example # 2, we create a variable named http. The value of that variable is the Node.js http module. This module is part of in the core Node.js base, so there is no need to reference it in package.json. The http module has properties and methods, but the one we have used is createServer. This does the heavy-lifting for us with regards to creating a web server. Pretty amazing. We have passed an anonymous function to the createServer method, so now we can take a look at that function.

The anonymous function that we pass as an argument takes the request object and the response object as arguments. In all code examples, these arguments are the variables: req and res. The request object represents the request from the user, and it has a properties and methods. The response object represents the response that the Node.js server can send back to the user. It also has properties and methods. For this article, we focus on the response object.

We use the variable res to access the response object, which has a method named writeHead. This creates an HTTP header. An HTTP header helps your browser how to process the HTTP communication. The first argument we pass to the writeHead method is the number 200. This is an http status code. The code 200 means: "The request has succeeded." The second argument is an object that can contain more or more headers. We set the Content-Type header, using a value of text/html to let the browser know how to process the body of the response. In this case, it tells the browser to parse the body as HTML (as opposed to say JavaScript or CSS).

The second task we take-up in this anonymous callback is ca call to response.end. This method tells the server that we have finished sending the response headers and body. It also tells the server that this message is complete. The response.end method offers some flexibility; it allows us to pass data as the first argument. This has the same effect as calling response.write and then response.end. The main thing to keep in mind here is that we end the response, passing some content that we want sent to the browser.

The last task we take-up is: a call to the server.listen method. Notice that earlier, we created a variable named server. The work we did when we called http.createServer returns an object. This object has methods, and one of them is the listen method. This method tells our server to listen for an HTTP request. Without it, our server would not function at all. We pass the number 3000 as an argument to the server.listen method. This tells the server which port to listen on. We could run another instance of this server and tell it to listen on port 3001. And then we could run another instance could listen on port 3002, and so on.

Speaking of ports, it is important to keep mind that for each instance of or server, you need to add the port to the URL in your browser. For example: localhost:3000.

The last line of example # 2 is a console message which you will see on your local machine. It just informs us that the server has started up with success.

Example # 3:


var htmlString = ''
  + ''
  + ''
    + ' '
      + ' '
      + 'My first Node.js web server'
    + ''
    + ' '
      + '

This is real HTML!

' + ' ' + ''; //set a reference to the http module var http = require('http'); //call the http module's createServer method, to create a server instance var server = http.createServer(function (req, res) { //access the response object, and create a Content-Type header res.writeHead(200, {'Content-Type': 'text/html'}); //end the response, sending some text (the user will see this in their browser) res.end(htmlString); }) //tell the server to listen for requests server.listen(3000); //just lets us know that the server is running console.log('In your browser, go to: http://localhost:3000');

Not a lot has changed in example # 3. What we have modified is the text sent to the res.end method. The htmlString variable at the top of the file contains a string of HTML. This HTML is simple. In fact, most of it is the HTML, HEAD and BODY tags. This ensures that our HTML response has a valid structure. The purpose of example # 3 is to show that you can send fully valid HTML as a response.

Summary

Hopefully this article has helped to demystify the concept of setting-up a web server with Node.js. Even though our example # 1 features limited functionality, it was a proof of concept. The main take-away here is that the level of effort required to get a Node.js web server running is minimal. Once your application grows in complexity, your code base will surely increase. What I have tried to impress here is that the high-level concepts in-play here are less complicated than one may think. There are three steps: reference the HTTP module, create a server instance, and then wait for requests. Just about anything you might do with your Node.js server will build upon this simple scenario.

Share This