Node Js : Module system and npm

In order to structure your program into different files, node.js provides you with a simple module system. Lets us rewrite our helloWorld.js in the following way:


function helloWorld() {
  console.log('Hello World');
}

module.exports.helloWorld=helloWorld;

Whatever function you have written in your js file private. In order to use it in other files you have to export it using module.exports. (you could use exports.functionName = function(){-code-}; also, but previous one looks cleaner)

Lets have a main.js with


var test = require('./helloWorld');
test.helloWorld();

The require(‘./helloWorld’) 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 you don’t have to provide the file extension, as ‘.js’ is assumed by default. If we run this main.js, it will print Hello World.

Lets write a program to read file. We will first write a synchronous version. Node has a build in fs module which deals with file I/O. It has a readFile method to read the contents of a file. In node all Synchronus function are named Sync at the end. Function with no Sync at the end are usually asynchronus.


var fs =require('fs');
console.log("Start program");
var fileData=fs.readFileSync("./test.txt");
console.log("File Contents::");
console.log(fileData.toString()); // fileData will just print a buffer.
console.log("After reading");

Output :


>node readSync.js
Start program
File Contents::
This is from test.txt line 1
This is from test.txt line 2
After reading

As you notice that in order to make it in a readable format , we had to use toString() methods because in node every data transfer is done not by string but by using an array buffer.

Now lets write the same in asynchronus way. Callback functions are the basic building block of asynchronous event-driven programming in Node.js. They are functions passed as an argument to an asynchronous I/O operation. They are called once the operation is finished.


var fs =require('fs');
console.log("Start program");
fs.readFile("./test.txt",function(error,fileData){
  console.log("File Contents::");
  console.log(fileData.toString());
});
console.log("After reading");

So for async we use jus tthe readFile method which takes 2 parameters. File name and a callback fucntion. In node almost all the callbak functions are error first callback syntax, i.e the first parameter is always reserve for an error. Output:


>node readAsync.js
Start program
After reading
File Contents::
This is from test.txt line 1
This is from test.txt line 2

As we can see, node didn’t stopped to wait for the file reading to complete and carried on to the next line. Lets modify the code to handle errors with a simulation like say , DB call or webservice call etc.


var fs =require('fs');
console.log("Start program");
fs.readFile("./test.txt",function(error,fileData){
if(error){
console.error("error::"+error);
}else{

setTimeout(function(){
console.log("File Contents::");
console.log(fileData.toString());
},1000);

}
});
console.log("After reading");

So, if there is an error, it will print out the error, else print out the data after a pause of 1 sec.

NPM is a package management and distribution system for Node. You can use it to install and publish your node programs. NPM is built in node, so while installing node we also got npm. Its similar to tools like apt-get (Debian), rpm/yum (Redhat/Fedora) etc. With npm you can quickly find packages to serve specific purposes, download them, install them, and manage packages you’ve already installed.

NPM web page npmjs.org is where you can search all the available modules. Lets use a third party module to get the file name as an argument. We would be using minimist module. To install simply type

> npm install minimist

minimist_install

We will now change our async file code to have a function now that takes filename and a callback as a parameter. We then use the readFile method from the fs inbuild module as before. Instead of printing the contents here, we will simply call the callback function. we will then have the function be exported so that other files can use it.


var fs =require('fs');

function readTheFile(filename,callback) {
console.log("Start program");
fs.readFile(filename,function(error,fileData){
    if (error) {
       callback(error);
     }
     else {
       setTimeout(function(){
          callback(null,fileData);
       },1000);
     }
});
console.log("After reading");
}
module.exports.readTheFile = readTheFile;

We now write a main js file that calls the our readTheFile method written previously. We use the minimist module here which takes the second argument and gets the valus of the file. We also have written a help fucntion so that it would be easy to understand how to use this utility.


function printHelp() {
  console.log("Reading File Basics");
  console.log("");
  console.log("--help              print this help");
  console.log("--file={FILENAME}   which file to load");
  console.log("");
  console.log("");
}

var args = require("minimist")(process.argv.slice(2),{ string: "file" });

if ("help" in args || !args.file) {
  printHelp();
  process.exit(1);
}

var reader = require("./readAsync.js");

reader.readTheFile(args.file,function(err,msg){
  if (err) {
    console.error("Error: " + err);
  }
  else {
    console.log(msg.toString());
  }
});

Output for few argumets:

minimist_readFileBasic

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: