0

Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

Node.js allows us to run JavaScript code in the backend, outside a browser. In order to execute the JavaScript we intend to run in the backend, it needs to be interpreted and well executed. Node.js ships with a lot of useful modules, so we don't have to write everything from scratch.

Node.js Installation

With NVM (Node version manager) we can have multiple versions of Node installed on our system and switch between them easily. In the next few lines we are going to see how to install NVM on an Ubuntu system. First, we have to make sure our system has a C++ compiler.

$ sudo apt-get update
$ sudo apt-get install build-essential libssl-dev

After that we will execute the following command into the terminal for NVM

$ curl https://raw.githubusercontent.com/creationix/nvm/v0.13.1/install.sh | bash

At this moment NVM should be properly installed.

$ nvm

If there's no error when typing in the nvm command, that means everything is alright. Now we can move on to install Node.

$ nvm install v0.10.31

The output should look like this:

$ nvm install v0.10.31

###################################################### 100.0%

Now using node v0.10.31

Node Package Manager (NPM) is the largest ecosystem of open source libraries in the world. It is used to install node programs. NPM comes bundled with Node.js installables after v0.6.3 version. Basically NPM provides two main functionalities −

  • Online repositories for node.js packages/modules which are searchable on search.nodejs.org
  • Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.

Now, we need to do one more thing, so that we can always use this version of Node when we login the next time: making this version the default one.

$ nvm alias default 0.10.31

We can install other Node versions just like we did before and switch between them with the nvm use command:

$ nvm install v0.8.10
$ nvm use v0.8.10

If we are not sure regarding what versions we have installed in our system, we can see the list of nvm installed by just typing nvm list. That will show the full list of versions and also the current and default versions, such as the following:

$ nvm list
v0.6.3 v0.6.12 v0.6.14 v0.6.19 v0.7.7 v0.7.8 v0.7.9 v0.8.6 v0.8.11 v0.10.3 v0.10.12 v0.10.15 v0.10.21 v0.10.24 v0.11.9 current: v0.10.24 default -> v0.10.24

If everything works fine, we should be able to invoke the interactive node.js shell like this

$ node
> console.log('Hello World');
Hello World

The interactive shell (also called REPL) is a great place to test simple one liners, and can also be directly embedded into our node.js applications. In order to get out of it, we can simply press Ctrl + C. The REPL also comes with many other great features, most importantly tab auto-completion.

Run simple code in terminal

For getting started, we need to create a folder, say nodeJs. Once we navigate into it, run

$ npm init

This command creates a package.json file in that folder which helps us to manage dependencies that we will need to install when proceed with new module such as express.Then just continuing hitting enter through everything that appears on the terminal.

To start with a simplest code, we will create a javascript file in the nodeJs folder.

$ touch server.js

Then we will write a simple console.log statement in server.js:

console.log('First try with Node')

Now to run server.js, we will use

node server.js

This will output "First try with Node" message in the terminal.

Module in Node

A module encapsulates related code into a single unit of code. This can be interpreted as moving all related functions into a file. Node implements the CommonJS interface for modules. In Node we can also load other dependencies using the require keyword.

For example, we can require some native modules:

var http = require('http');

Importing a Module

Suppose, we create a file called greetings.js which contains the following two functions:

// greetings.js

sayHelloInEnglish = function() {
  return "Hello";
};

sayHelloInSpanish = function() {
  return "Hola";
};

Now, We can import all the publicly available methods of greetings.js to a new file called main.js.

// main.js

var greetings = require("./greetings");

Here, the require('./greetings) is used to import the contents from another JavaScript file. The initial './' indicates that the file is located in the same directory as 'main.js'. Also note that we don't have to provide the file extension, since '.js' is assumed by default.

Now, if we want to access the methods of greetings

// main.js
var greetings = require("./greetings.js");

greetings.sayHelloInEnglish();
greetings.sayHelloInSpanish();

In order to write all the greeting content in a single javascript, we need to proceed with the following

// main.js

var greetings = {
  sayHelloInEnglish: function() {
    return "HELLO";
  },

  sayHelloInSpanish: function() {
    return "Hola";
  }
};

How module deals with require?

var http = require('http');

In case of core module, It first looks if there is a core module named http, and since that's the case, return that directly.

But what about non-core modules, such as 'mysql'?

var mysql = require('mysql');

In this case node.js will walk up the directory tree, moving through each parent directory in turn, checking in each to see if there is a folder called 'node_modules'. If such a folder is found, node.js will look into this folder for a file called 'mysql.js'. If no matching file is found and the directory root '/' is reached, node.js will give up and throw an exception.

Node with http server

We will create a javascript file named helloHttp.js and put the following code into it.

var http = require('http');

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

At first, we include the http core module by using require and assign it to a variable called http and makes it accessible through the variable http. We then call one of the functions the http module offers and that is createServer. The argument passed into this call is a closure that is called whenever an http request comes in. This function returns an object, and this object has a method named listen, and takes a numeric value which indicates the port number on which our HTTP server is going to listen.

Now when we browse to 'localhost:8080', the connection closure will be invoked with a req and res object. The req is a readable stream that emits 'data' events for each incoming piece of data. The res object is a writable stream that is used to send data back to the client. In our case we are simply sending a 200 OK header, as well as the body 'Hello Http'.

Whenever any changes made in the javascript file, we need to stop the server by pressing Ctrl + C and then again start the server in order to see the changes. Otherwise, we cannot see the changes in the output.

Why Nodemon

It’s so tedious to stop and start server every time when making any changes in the file. Nodemon restarts the server automatically whenever we save a file that the server uses. We can install Nodemon by using the following command

$ npm install nodemon --save-dev

The reason we’re using a --save-dev flag here is because we’re only using Nodemon when we’re developing. This flag would save Nodemon as a devDependency in your package.json file. Moving on, Nodemon behaves like node, which means we can run our server by calling nodemon server.js. However, we can’t do it in the command line right now because Nodemon isn’t installed with a -g flag. There’s one other way to run Nodemon – we can execute Nodemon from the node_modules folder. The code looks like this:

$ ./node_modules/.bin/nodemon server.js

That’s a handful to type. One way to make it simpler is to create a script key in package.json.

{
  // ...
  "scripts": {
    "dev": "nodemon server.js"
  }
  // ...
}

Now, we can run npm run dev to trigger nodemon server.js.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí