Search code examples
javascriptnode.jsmongodbbackbone.jsexpress

How to setup NodeJS server and use NodeJS like a pro


There is few general question:

  • How to install NodeJS?
  • Using NodeJS packages
  • Which tools to use for creating simple API with NodeJS?
  • The best NodeJS boilerplates?
  • What is the next steps to became a NodeJS professional?

Solution

  • NodeJS is JS runtime built on Chrome V8 JavaScript engine. NodeJS uses event-driven, non-blocking I/O model - that makes it lightweight and efficient.

    NodeJS has a package system, called npm - it's a largest ecosystem of open source libraries in the world.

    Current stable NodeJS version is v4.0.0 - it's included new version of V8 engine and ES6 features.

    NodeJS installation (on Ubuntu) is very simple process, you should run only two commands in your trminal:

    sudo apt-get update

    sudo apt-get install nodejs

    Also we should install package system: sudo apt-get install npm

    For managing installed NodeJS versions on our server, I used "tj/n" tool. We can install it using NPM: npm install -g n

    The simple http-server on NodeJS looks like this:

    var http = require('http');
    
    http.createServer(function (request, response) {
      response.writeHead(200, {'Content-Type': 'text/plain'});
      response.end('Hello World\n');
    }).listen(8124);
    
    console.log('Server running at http://127.0.0.1:8124/');
    

    For handling requests from different URL we can use package "httpdispatcher"

    For creating more complex applications using NodeJS we need more complex solutions. At this point we can start to use NodeJS framework - Express

    Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

    We can install Express in our project using npm: npm install express --save

    When we using Express we've got a lot cool things, such as:

    • Routing - it's a pretty simple to use API which helps resolve a lot of things, such as creating REST API for your project.
    • Template Engine - one of the most demanded frameworks features. With express framework we can use any compatible templates engine, Most popular - Jade. We can install Jade to our project using NPM: npm install jade --save and then we can use it.
    • Database integration - in NodeJS+Express it's just installation NodeJS driver for the DB in your APP. There is a lot of databases we can use. Each DB-drive has a specific API, which we get after including in our project

    To create API you for your project you can use LoopBack - is a highly-extensible, open-source Node.js framework. If you need fast develop your API - it's the best way.

    Also to start your project with NodeJS, you can use boilerplates, such as: