Node.js

Node is an open source runtime environment for server-side applications. It allows you to run JavaScript on the server in addition to the browser. Almost all of the new and most widely used JavaScript solutions use Node in one form or another.

Installing Node.js

Download from https://nodejs.org. Install with default options. To check, type the following on the terminal

$ which node
node --version

Installing Brackets

You can use any non-formatting text editor for Node such as Notepad++ or Sublime Text. I used Brackets because it is a great text editor for JavaScript development. If you would like to try it, following are the installation steps.

  1. Download it from here http://brackets.io
  2. Download and install the latest stable version
  3. Start up brackets
  4. In the top menu, go to Node.js > Configuration…
  5. Type in the the addresses of Node and NPM binaries. If you don't know the addresses, run the following commands on the terminal to find the addresses:

    $ which node $ which npm

Save your changes and enjoy using brackets

Hello World

Type the following command in your editor of choice.

console.log(“Hello World”);

Save this file as hello.js. You can run it within Brackets by simply clicking on Node.js > Run. If you are not using Brackets, you can run it from command line by typing the following:

$ node hello.js

Node Package Manager

Node Package Manager (npm) comes bundled with Node. It allows you do search Node repositories for packages and modules. Anything that is searchable on search.nodejs.org is also searchable by npm. npm can be used to install Node packages on your system. It also performs version and dependency management for all Node packages installing on your system. To find out the version of npm you are using, simply type the following command

$ npm --version
2.15.9

To upgrade you npm,

$ sudo npm install npm -g
/usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
npm@3.10.6 /usr/local/lib/node_modules/npm
$ npm --version
3.10.6

To install a module

$ npm install express

where express is a module. Express.js is now installed in the local Node repository. To use it, you will need to require it as follows:

var ex = require(‘express’);

To list all installed modules

$ npm ls

To uninstall a module

$ npm uninstall express

By default all modules are installed locally. They are only visible in the directory and subdirectories or the directory you were in when you ran npm install. To make the a module visible globally (to all applications in your system), you need to install it globally as follows:

$ sudo npm install express -g

This will install the module to /usr/local/lib or some other global location. To view globally installed modules

$ npm ls -g

To update a module

$ npm update express

Start Coding

Let's start with a very simple program:

console.log("Hello World");

Save as hello.js. In the command line, type the following to run it:

$ node hello.js

Next add a variable:

var hello = "Hello World!";
console.log(hello);

The output of this program should be the same as the previous program.

Following program shows how to use a library:

var path = require("path");
console.log(`The path is ${path.basename(__filename)}`);

Note the use of backtick characters. ${} is use to get value of the function.

Process Object

The process object is available globally meaning that it can be accessed from anywhere in the code. It allows us to fetch information regarding the current process instance; information such as environmental variables, path, stdin, and stdout.

console.log(process.argv);

Save this code as processdemo.js. To run:

$ node processdemo.js

This code outputs the parameters used when the process starts. It's output is as follows:

[ '/usr/bin/node', '/Users/testing/exercises/processdemo.js' ]

If I run the command with parameters:

$ node processdemo.js id name

The output will be:

[ '/usr/bin/node', '/Users/testing/exercises/processdemo.js' ,'id','name']

To get an individual parameter, simply print the specific element in the process.argv array by it's index

console.log(process.argv[3]);

will output:

name

process.stdout.write prints to the terminal. process.stdin.on adds a listener event. See the example below.

var question = "Say something?";
var answer = "";

function prompt() {
  process.stdout.write(`\n ${question}: `);
}

process.stdin.on('data', function(data) {
  answer = data.toString().trim();
  process.exit();
});

process.on('exit', function() {
  process.stdout.write(`\nYou said ${answer}\n`);
});

prompt();

In this program, we begin from the call to prompt() function at the bottom. prompt() function prints the question to the terminal using stdout.write function(). process.stdin.on('data'...) is an event listener that listens for data. Once you type something and hit return, process.on('exit'..) function is called. It prints your response to the question.

Synchronous and Asynchronous communication

Node support both synchronous and asynchronous communication. What is the difference? Synchronous communication is sequential communication. You can only run one job at a time and all jobs need to wait for their turn to run. In asynchronous communication, the jobs can run in parallel depending on available resources. Following is a simplified example.

Suppose you call your Internet service provider and need to speak to a representative. You will be placed on hold until someone becomes available. This is synchronous communication. You are put on hold and you cannot do anything else. Some companies give you the option of a callback. You call in and leave a callback number. When a representative is free, he or she will call you back. You are free to do other things until you turn comes up. You are not on hold. This is asynchronous communication.

In asynchronous programming, a callback is equivalent of function. It is called after a task is completed.

Following code will synchronously list contents of a directory:

fh = require(‘fs’);
content = fh.readdirSync(‘mydirectory’);
console.log(content);

Following code will asynchronously list contents of a directory

fh = require(‘fs’);
content = fh.readdir(‘mydirectory’);
console.log(content);

Except for the function name, the rest is the same.

Events

Node.js is an event-driven system. When you are performing different tasks, different events are emitted. You need to understand those events and use them. You will see the use of EventEmitter in later in this writing.

Streams

Data can come from or go to many different sources such as text files, JSON, and XML. Streams are objects that allow you to read from or write to a data source.

EventEmitters for streams are:

  • Data: when data is available for reading
  • End : when there is no more data to read
  • Error: where there is an error read from or writing to a stream
  • Finish: when you are done using the stream

The following code show how to read from a file using these EventEmitters:

var fs = require("fs");
var content = '';

// open file and create stream for reading
var rs = fs.createReadStream('in.txt');

// read from the file
rs.on('data', function(txt) {
  console.log(txt);    
  content += txt;
  console.log(content);
});

// done reading
rs.on('end', function(){
  console.log('done reading');
})

// print any errors          
rs.on('error', function(err){
  console.log(err.stack);
})   

Save this file as readfromfile.js. Create a text file, in.txt with the following contents and save in the same directory as readfromfile.js.

one
two
three

The output:

<Buffer 6f 6e 65 0a 74 77 6f 0a 74 68 72 65 65>
one
two
three
done reading

Note that the first line output is the print out of the stream, so it is a buffer. When we assign the buffer to a text variable, it is converted to string data.

Code to append to a file, simply use the following code

var fs = require("fs");
var as = fs.appendFile('in.txt','four');

It appends the word four to the file. To write to a new file,

var fs = require("fs");
var content = 'Four';

// write stream to file
var ws = fs.createWriteStream('out.txt');
ws.write(content);
ws.end();

ws.on('error', function(err){
  console.log(err.stack);
});

This code writes the word Four in out.txt file. If the file does not exist, it will create it. If it exists, it will be overwritten. The following code pipes contents of an input file into an output file.

var fs = require("fs");

// create read and write streams and pipe them
var rs = fs.createReadStream('in.txt');
var ws = fs.createWriteStream('out.txt');
rs.pipe(ws);

Utility Modules

Node has many utility modules. You have already used the fs module, which provides file and stream manipulation functions. Following are some of the commoly used modules.

  • DNS module: provides DNS related functionalities
  • Domain modules: handling I/O operations
  • FS module: File and stream functions
  • HTTP module: Handling http communications. Very important for web development.
  • Net module: Provides client and server streams
  • OS module: provides operating system utility functions
  • Path module: provides utility functions to manipulate file paths.

In addition to the standard utility modules, there are numerous contributed modules such as Express.js.

Web Development

http module can be used to create a web server and a client. It can also be used to handle REST API and SOAP messages. However, using http module alone can get complicated. Currently, the industry standard is to use a middleware such as Express.js for such work. I would therefore encourage you to learn a middleware tool as this point. Express.js is a good one to start with.

Conclusion

The goal of this writing is to get you started with Node.js and npm. It is a starting point for JavaScript development. You can continue learning more about Node.js or move on to one of the many tools that use Node.js but are more focused toward specific goals such as building web pages. A popular solution is the MEAN stack. It includes MongoDB, Express, Angular, and Node.js. MongoDB or Express should be the next logical step followed by Angular.

Technologies: