Node JS server

Node.js first steps

Node.js is open source JavaScript runtime built on Chrome’s V8 JavaScript engine. Its lightweight and highly efficient, a lot of the popular io multiplayer games currently use Node.js as backend.

This tutorial assumes that you have basic understanding of JavaScript, HTML and CSS.

The basics

This part will help you install node.js and create very simple Hello World server.

Installation

Get the current version of node.js for your operating system from the official site https://nodejs.org/en/download/. Installation is pretty straight forward and intuitive. If you have any problems this link will open the official installation documentation page https://nodejs.org/en/download/package-manager/.

First Server

After installing it you can check if node.js works by typing node in the shell:

>node
>console.log("Hello Node");
Hello Node

You can add the row above in a file hello.js and run it:

console.log("Hello Node");
>node hello.js
Hello Node

Now if we want simply to write in console we would use something else. Its time to create our first http server – Hello Node server.
Here is the code for it – helloserver.js:

var http = require('http');

var server = http.createServer(function(req, res) {
  res.writeHead(200);
  res.end('Hello Node');
});

server.listen(9009);

And now we can run our server:

>node helloserver.js

And to test our server we can open the url http://localhost:9009/ in our browser:

Node JS server

In the example above we used the require directive to load the http module and then we stored the returned instance into our variable http:

var http = require('http');

Then we call the createServer method to actually create our http server. Then we bind our server to listen on port 9009.

server.listen(9009);

Modules

In NodeJS we use the keyword require to load modules.

var http = require('http');

Require can be used with relative path:

var mymodule = require('./mymodule');

The code above will load mymodule from mymodule.js.

NodeJS supports concurrency through events and callbacks.

Callbacks

NodeJS programming relies strongly on asynchronous programming – an asynchronous function calls a callback function when ready. Most of the time we pass a callback function to modules, and that function will be called when ready.

Events

Node applications are event-driven applications – they listen for events and then a callback function is triggered. It looks similar to callbacks but event-listeners are a bit different. You can learn more about them by reading about the Observer pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *