Thursday, July 11, 2013

Create, Load & Export Module in Node.js

Nowadays, javascript development is getting broader in web development.
Either on front-end (JQueryKnockoutJSTypeScript, etc) or back-end (Node.js, ect), more libraries are created with more compact, more light-weight.

Today, i'll show the basic setup of Node.js.
From wikipedia, Node.js is a server-side software system designed for writing scalable Internet applications, notably web servers. It's akin to IIS in Windows, or Apache Tomcat in world of Java.

1) Download and install from official website.

2) Upon successful of installation, you should able to see several shortcut created in the "Start" menu.


3) Launch the "Node.js" . This is the place where you can issue all the Node.js related commands.

4) To find out the current execution path, we can execute this "Path" command:

process.env.PATH.split(path.delimiter)

5) Two additional environment PATHs are created:


6) For "Loading a File Module", create a "circle.js" (see code below) from official user manual, and place in Node.js environment PATH:

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};


7) Execute this in "Node.js":

var circle = require('./circle.js');circle.area(4);

8) and you should get your result:


9)  For "Loading a Folder Module" or so called user-defined library, it needs few more steps. Create a folder called "a" in Node.js environment PATH.


10) Create a file called "package.json" (see code below):

{
 "name" : "some-library",
 "main" : "./lib/b.js"
}

11) Create a folder called "lib" in folder "a" and another file called "b.js" (this is the file mentioned above in "package.json"; see code below) in folder "lib":

console.log('module b initializing...');

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

console.log('b initialized.');

12) Execute the following command:

var circle = require('./a');circle.area(4);


13) That's it!

1 comment:

Blogger said...

BlueHost is one of the best hosting provider for any hosting services you might require.