Everything else is an object in Node.js.
JavaScript in Node.js supports loose typing like the browser's JavaScript. Use var keyword to declare a variable of any type.
Object literal syntax is same as browser's JavaScript.
var obj = { authorName: 'Ryan Dahl', language: 'Node.js' }
Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript. A function can have attributes and properties also. It can be treated like a class in JavaScript.
function Display(x) { console.log(x); } Display(100);
Node.js includes an additional data type called Buffer (not available in browser's JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network.
Node.js comes with virtual environment called REPL (aka Node shell). REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.js/JavaScript code.
To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node as shown below. It will change the prompt to > in Windows and MAC.
D:\nodejs_mongodb_project\allProject> node console.log("hi node"); enter D:\nodejs_mongodb_project\allProject> node test.js enterTo exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.
D:\nodejs_mongodb_project\allProject> exit enter
Each Node.js script runs in a process. It includes process object to get all the information about the current process of Node.js application.
The following example shows how to get process information in REPL using process object.
> process.execPath 'C:\\Program Files\\nodejs\\node.exe' > process.pid 1652 > process.cwd() 'C:\\'
Node's JavaScript is different from browser's JavaScript when it comes to global scope. In the browser's JavaScript, variables declared without var keyword become global. In Node.js, everything becomes local by default.
In a browser, global scope is the window object. In Node.js, global object represents the global scope.
To add something in global scope, you need to export it using export or module.export. The same way, import modules/object using require() function to access it from the global scope.
For example, to export an object in Node.js, use exports.name = object.
exports.log = { console: function(msg) { console.log(msg); }, file: function(msg) { // log to file here } }
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate .js file under a separate folder.
Node.js implements CommonJS modules standard. CommonJS is a group of volunteers who define JavaScript standards for web server, desktop, and console application.
Node.js is a light weight framework. The core modules include bare minimum functionalities of Node.js. These core modules are compiled into its binary distribution and load automatically when Node.js process starts. However, you need to import the core module first in order to use it in your application.
In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below. As per above syntax, specify the module name in the require() function. The require() function will return an object, function, property or any other JavaScript type, depending on what the specified module returns. The following example demonstrates how to use Node.js http module to create a web server. Local modules are modules created locally in your Node.js application. These modules include different functionalities of your application in separate files and folders. You can also package it and distribute it via NPM, so that Node.js community can use it. For example, if you need to connect to MongoDB and fetch data then you can create a module for it, which can be reused in your application. Let's write simple logging module which logs the information, warning or error to the console. In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file and write the following code in it. In the above example of logging module, we have created an object with three functions - info(), warning() and error(). At the end, we have assigned this object to module.exports. The module.exports in the above example exposes a log object as a module. The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js. To use local modules in your application, you need to load it using require() function in the same way as core module. However, you need to specify the path of JavaScript file of the module. The following example demonstrates how to use the above logging module contained in Log.js. In the above example, app.js is using log module. First, it loads the logging module using require() function and specified path where logging module is stored. Logging module is contained in Log.js file in the root folder. So, we have specified the path './Log.js' in the require() function. The '.' denotes a root folder. The require() function returns a log object because logging module exposes an object in Log.js using module.exports. So now you can use logging module as an object and call any of its function using dot notation e.g myLogModule.info() or myLogModule.warning() or myLogModule.error() Run the above example using command prompt (in Windows) as shown below. Thus, you can create a local module using module.exports and use it in your application. Here, you will learn how to expose different types as a module using module.exports. The module.exports is a special object which is included in every JavaScript file in the Node.js application by default. The module is a variable that represents the current module, and exports is an object that will be exposed as a module. So, whatever you assign to module.exports will be exposed as a module. As mentioned above, exports is an object. So it exposes whatever you assigned to it as a module. For example, if you assign a string literal then it will expose that string literal as a module. The following example exposes simple string message as a module in Message.js. Now, import this message module and use it as shown below. Run the above example and see the result, as shown below. You must specify ./ as a path of root folder to import a local module. However, you do not need to specify the path to import Node.js core modules or NPM modules in the require() function. The exports is an object. So, you can attach properties or methods to it. The following example exposes an object with a string property in Message.js file. In the above example, we have attached a property SimpleMessage to the exports object. Now, import and use this module, as shown below. In the above example, the require() function will return an object { SimpleMessage : 'Hello World'} and assign it to the msg variable. So, now you can use msg.SimpleMessage. Run the above example by writing node app.js in the command prompt and see the output as shown below. In the same way as above, you can expose an object with function. The following example exposes an object with the log function as a module. The above module will expose an object- { log : function(msg){ console.log(msg); } } . Use the above module as shown below. Run and see the output in command prompt as shown below. You can also attach an object to module.exports, as shown below. You can attach an anonymous function to exports object as shown below. The msg variable becomes a function expression in the above example. So, you can invoke the function using parenthesis (). Run the above example and see the output as shown below. In JavaScript, a function can be treated like a class. The following example exposes a function that can be used like a class. The above module can be used, as shown below. In this way, you can export and import a local module created in a separate file under root folder. Node.js also allows you to create modules in sub folders. Let's see how to load module from sub folders. Use the full path of a module file where you have exported it using module.exports. For example, if the log module in the log.js is stored under the utility folder under the root folder of your application, then import it, as shown below.
In the above example, . is for the root folder, and then specify the exact path of your module file. Node.js also allows us to specify the path to the folder without specifying the file name. For example, you can specify only the utility folder without specifying log.js, as shown below.
In the above example, Node.js will search for a package definition file called package.json inside the utility folder. This is because Node assumes that this folder is a package and will try to look for a package definition. The package.json file should be in a module directory. The package.json under utility folder specifies the file name using the main key, as shown below. Now, Node.js will find the log.js file using the main entry in package.json and import it. If the package.json file does not exist, then it will look for index.js file as a module file by default. Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls Node.js packages in your application. It is also an online repository for open-source Node.js packages. The node community around the world creates useful modules and publishes them as packages in this repository. Official website: https://www.npmjs.com NPM is included with Node.js installation. After you install Node.js, verify NPM installation by writing the following command in terminal or command prompt. If you have an older version of NPM then you can update it to the latest version using the following command. To access NPM help, write npm help in the command prompt or terminal window. NPM performs the operation in two modes: global and local. In the global mode, NPM performs operations which affect all the Node.js applications on the computer whereas in the local mode, NPM performs operations for the particular local directory which affects an application in that directory only. Use the following command to install any third party module in your local Node.js project folder. For example, the following command will install ExpressJS into MyNodeProj folder. All the modules installed using NPM are installed under node_modules folder. The above command will create ExpressJS folder under node_modules folder in the root folder of your project and install Express.js there. Use --save at the end of the install command to add dependency entry into package.json of your application. For example, the following command will install ExpressJS in your application and also adds dependency entry into the package.json. The package.json of NodejsConsoleApp project will look something like below. NPM can also install packages globally so that all the node.js application on that computer can import and use the installed packages. NPM installs global packages into / Apply -g in the install command to install package globally. For example, the following command will install ExpressJS globally. To update the package installed locally in your Node.js project, navigate the command prompt or terminal window path to the project folder and write the following update command. Use the following command to remove a local package from your project. In this section, we will learn how to create a simple Node.js web server and handle HTTP requests. To access web pages of any web application, you need a web server. The web server will handle all the http requests for the web application e.g IIS is a web server for ASP.NET web applications and Apache is a web server for PHP or Java web applications. Node.js provides capabilities to create your own web server which will handle HTTP requests asynchronously. You can use IIS or Apache to run Node.js web application but it is recommended to use Node.js web server. Node.js makes it easy to create a simple web server that processes incoming requests asynchronously. The following example is a simple Node.js web server contained in server.js file. In the above example, we import the http module using require() function. The http module is a core module of Node.js, so no need to install it using NPM. The next step is to call createServer() method of http and specify callback function with request and response parameter. Finally, call listen() method of server object which was returned from createServer() method with port number, to start listening to incoming requests on port 5000. You can specify any unused port here. Run the above web server by writing node server.js command in command prompt or terminal window and it will display message as shown below. This is how you create a Node.js web server using simple steps. Now, let's see how to handle HTTP request and send response in Node.js web server. The http.createServer() method includes request and response parameters which is supplied by Node.js. The request object can be used to get information about the current HTTP request e.g., url, request header, and data. The response object can be used to send a response for a current HTTP request. The following example demonstrates handling HTTP request and response in Node.js. This is home Page. This is student Page. This is admin Page. In the above example, req.url is used to check the url of the current request and based on that it sends the response. To send a response, first it sets the response header using writeHead() method and then writes a string as a response body using write() method. Finally, Node.js web server sends the response using end() method. To test it, you can use the command-line program curl, which most Mac and Linux machines have pre-installed. You should see the following response. The following example demonstrates how to serve JSON response from the Node.js web server. So, this way you can create a simple web server that serves different responses. Node.js includes fs module to access physical file system. The fs module is responsible for all the asynchronous or synchronous file I/O operations. Use fs.readFile() method to read the physical file asynchronously. Parameter Description: The following example demonstrates reading existing TestFile.txt asynchronously. The above example reads TestFile.txt (on Windows) asynchronously and executes callback function when read operation completes. This read operation either throws an error or completes successfully. The err parameter contains error information if any. The data parameter contains the content of the specified file. ou can debug Node.js application using various tools including following: Node.js provides built-in non-graphic debugging tool that can be used on all platforms. It provides different commands for debugging Node.js application. Write debugger in your JavaScript code where you want debugger to stop. For example, we want to check the "data" parameter in the above example. So, write debugger; inside callback function as above. Now, to debug the above application, run the following command. In this section, we will use node inspector tool to debug a simple Node.js application contained in app.js file. Node inspector is GUI based debugger. Install Node Inspector using NPM in the global mode by writing the following command in the terminal window (in Mac or Linux) or command prompt (in Windows). As you can see in the above figure, it will display an URL for debugging purpose. So, point your browser to http://127.0.0.1:8080/?ws=127.0.0.1:8080&port=5858 and start debugging. Sometimes, port 8080 might not be available on your computer. So you will get the following error. Cannot start the server at 0.0.0.0:8080. Error: listen EACCES. In this case, start the node inspector on a different port using the following command. Now, open another terminal window or command prompt in Windows and start debugging using the following command. Refresh the browser and you will see that it stops at the first line of the program as shown below. Now, debug the program as a normal program in Chrome developer tool. Also, use watch expression on the right pane or hover the cursor on the variable to see the value as shown below. Node.js allows us to create and handle custom events easily by using events module. Event module includes EventEmitter class which can be used to raise and handle custom events. The following example demonstrates EventEmitter class for raising and handling a custom event. In the above example, we first import the 'events' module and then create an object of EventEmitter class. We then specify event handler function using on() function. The on() method requires name of the event to handle and callback function which is called when an event is raised. The emit() function raises the specified event. First parameter is name of the event as a string and then arguments. An event can be emitted with zero or more arguments. You can specify any name for a custom event in the emit() function. You can also use addListener() methods to subscribe for an event as shown below. The following table lists all the important methods of EventEmitter class. There are two common patterns that can be used to raise and bind an event using EventEmitter class in Node.js In this pattern, a constructor function returns an EventEmitter object, which was used to emit events inside a function. This EventEmitter object can be used to subscribe for the events. Consider the following example. In the above LoopProcessor() function, first we create an object of EventEmitter class and then use it to emit 'BeforeProcess' and 'AfterProcess' events. Finally, we return an object of EventEmitter from the function. So now, we can use the return value of LoopProcessor function to bind these events using on() or addListener() function. In this pattern, we can extend the constructor function from EventEmitter class to emit the events. In the above example, we have extended LoopProcessor constructor function with EventEmitter class using util.inherits() method of utility module. So, you can use EventEmitter's methods with LoopProcessor object to handle its own events. You learned that we need to write lots of low level code ourselves to create a web application using Node.js in Node.js web server section. There are various third party open-source frameworks available in Node Package Manager which makes Node.js application development faster and easy. You can choose an appropriate framework as per your application requirements. The following table lists frameworks for Node.js. "Express is a fast, unopinionated minimalist web framework for Node.js" - official web site: Expressjs.com Express.js is a web application framework for Node.js. It provides various features that make web application development fast and easy which otherwise takes more time using only Node.js. Express.js is based on the Node.js middleware module called connect which in turn uses http module. So, any middleware which is based on connect will also work with Express.js. You can install express.js using npm. The following command will install latest version of express.js globally on your machine so that every Node.js application on your machine can use it. The following command will install latest version of express.js local to your project folder. As you know, --save will update the package.json file by specifying express.js dependency. ........ In this section, you will learn how to create a web application using Express.js. Express.js provides an easy way to create web server and render HTML pages for different HTTP requests by configuring routes for your application. First of all, import the Express.js module and create the web server as shown below. In the above example, we imported Express.js module using require() function. The express module returns a function. This function returns an object which can be used to configure Express application (app in the above example). The app object includes methods for routing HTTP requests, configuring middleware, rendering HTML views and registering a template engine. The app.listen() function creates the Node.js web server at the specified host and port. It is identical to Node's http.Server.listen() method. Run the above example using node app.js command and point your browser to http://localhost:5000. It will display Cannot GET / because we have not configured any routes yet. Use app object to define different routes of your application. The app object includes get(), post(), put() and delete() methods to define routes for HTTP GET, POST, PUT and DELETE requests respectively. The following example demonstrates configuring routes for HTTP requests. In the above example, app.get(), app.post(), app.put() and app.delete() methods define routes for HTTP GET, POST, PUT, DELETE respectively. The first parameter is a path of a route which will start after base URL. The callback function includes request and response object which will be executed on each request. Run the above example using node server.js command, and point your browser to http://localhost:5000 and you will see the following result. Here, you will learn how to handle HTTP POST request and get data from the submitted form. First, create Index.html file in the root folder of your application and write the following HTML code in it. To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser. The middleware was a part of Express.js earlier but now you have to install it separately. This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP POST request. Install body-parser using NPM as shown below. Now, import body-parser and get the POST request data as shown below. In the above example, POST data can be accessed using req.body. The req.body is an object that includes properties for each submitted form. Index.html contains firstName and lastName input types, so you can access it using req.body.firstName and req.body.lastName. Now, run the above example using node server.js command, point your browser to http://localhost:5000 and see the following result. Fill the First Name and Last Name in the above form and click on submit. For example, enter "James" in First Name textbox and "Bond" in Last Name textbox and click the submit button. The following result is displayed. This is how you can handle HTTP requests using Express.js. In this section, you will learn how to serve static resources like images, css, JavaScript or other static files using Express.js and node-static module. It is easy to serve static files using built-in middleware in Express.js called express.static. Using express.static() method, you can server static resources directly by specifying the folder name where you have stored your static resources. The following example serves static resources from the public folder under the root folder of your application. If you have different folders for different types of resources then you can set express.static middleware as shown below. You can also create a virtual path in case you don't want to show actual folder name in the url. So now, you can use http://localhost:5000/resources/myImage.jpg to serve all the images instead of http://localhost:5000/images/myImage.jpg. In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. In the above example, node-static will serve static files from public folder by default. So, an URL request will automatically map to the file in the public folder and will send it as a response.
Core Module
Description
http
http module includes classes, methods and events to create Node.js http server.
url
url module includes methods for URL resolution and parsing.
querystring
querystring module includes methods to deal with query string.
path
path module includes methods to deal with file paths.
fs
fs module includes classes, methods, and events to work with file I/O.
util
util module includes utility functions useful for programmers.
Loading Core Modules
var module = require('module_name');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
Local Module
var log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};
module.exports = log
var myLogModule = require('./Log.js');
myLogModule.info('Node.js started');
C:\> node app.js
Info: Node.js started
Export Module in Node.js
Message.js
module.exports = 'Hello world';
app.js
var msg = require('./Messages.js');
console.log(msg);
C:\> node app.js
Hello World
Message.js
exports.SimpleMessage = 'Hello world';
//or
module.exports.SimpleMessage = 'Hello world';
app.js
var msg = require('./Messages.js');
console.log(msg.SimpleMessage);
C:\> node app.js
Hello World
Log.js
module.exports.log = function (msg) {
console.log(msg);
};
app.js
var msg = require('./Log.js');
msg.log('Hello World');
C:\> node app.js
Hello World
data.js
module.exports = {
firstName: 'James',
lastName: 'Bond'
}
app.js
var person = require('./data.js');
console.log(person.firstName + ' ' + person.lastName);
C:\> node app.js
James Bond
Export Function
Log.js
module.exports = function (msg) {
console.log(msg);
};
app.js
var msg = require('./Log.js');
msg('Hello World');
Person.js
module.exports = function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function () {
return this.firstName + ' ' + this.lastName;
}
}
app.js
var person = require('./Person.js');
var person1 = new person('James', 'Bond');
console.log(person1.fullName());
C:\> node app.js
James Bond
app.js
var log = require('./utility/log.js');
app.js
var log = require('./utility');
./utility/package.json
{
"name" : "log",
"main" : "./log.js"
}
NPM - Node Package Manager
C:\> npm -v
2.11.3
C:\> npm install npm -g
C:\> npm help
C:\>npm install
C:\MyNodeProj> npm install express
C:\MyNodeProj> npm install express --save
package.json
{
"name": "NodejsConsoleApp",
"version": "0.0.0",
"description": "NodejsConsoleApp",
"main": "app.js",
"author": {
"name": "Dev",
"email": ""
},
"dependencies": {
"express": "^4.13.3"
}
}
Install Package Globally
C:\MyNodeProj> npm install -g express
Update Package
C:\MyNodeProj> npm update
Uninstall Packages
C:\>npm uninstall
Node.js Web Server
server.js
var http = require('http'); // 1 - Import Node.js core module
var server = http.createServer(function (req, res) { // 2 - creating server
//handle incomming requests here..
});
server.listen(5000); //3 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
C:\> node server.js
Node.js web server at port 5000 is running..
Handle HTTP Request
server.js
var http = require('http'); // Import Node.js core module
var server = http.createServer(function (req, res) { //create web server
if (req.url == '/') { //check the URL of the current request
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write('
C:\> node server.js
Node.js web server at port 5000 is running..
curl -i http://localhost:5000
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Tue, 8 Sep 2015 03:05:08 GMT
Connection: keep-alive
This is home page.
Sending JSON Response
server.js
var http = require('http');
var server = http.createServer(function (req, res) {
if (req.url == '/data') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Hello World"}));
res.end();
}
});
server.listen(5000);
console.log('Node.js web server at port 5000 is running..')
Node.js File System
fs.readFile(fileName [,options], callback)
Example: Reading File
var fs = require('fs');
fs.readFile('TestFile.txt', function (err, data) {
if (err) throw err;
console.log(data);
});
var fs = require('fs');
var data = fs.readFileSync('dummyfile.txt', 'utf8');
console.log(data);
Example: Creating & Writing File
var fs = require('fs');
fs.writeFile('test.txt', 'Hello World!', function (err) {
if (err)
console.log(err);
else
console.log('Write operation complete.');
});
Example: Append File Content
var fs = require('fs');
fs.appendFile('test.txt', 'Hello World!', function (err) {
if (err)
console.log(err);
else
console.log('Append operation complete.');
});
Open File
fs.open(path, flags[, mode], callback)
Example:File open and read
var fs = require('fs');
fs.open('TestFile.txt', 'r', function (err, fd) {
if (err) {
return console.error(err);
}
var buffr = new Buffer(1024);
fs.read(fd, buffr, 0, buffr.length, 0, function (err, bytes) {
if (err) throw err;
// Print only read bytes to avoid junk.
if (bytes > 0) {
console.log(buffr.slice(0, bytes).toString());
}
// Close the opened file.
fs.close(fd, function (err) {
if (err) throw err;
});
});
});
var fs = require('fs');
fs.unlink('test.txt', function () {
console.log('write operation complete.');
});
Important method of fs module
Method
Description
fs.readFile(fileName [,options], callback)
Reads existing file.
fs.writeFile(filename, data[, options], callback)
Writes to the file. If file exists then overwrite the content otherwise creates new file.
fs.open(path, flags[, mode], callback)
Opens file for reading or writing.
fs.rename(oldPath, newPath, callback)
Renames an existing file.
fs.chown(path, uid, gid, callback)
Asynchronous chown.
fs.stat(path, callback)
Returns fs.stat object which includes important file statistics.
fs.link(srcpath, dstpath, callback)
Links file asynchronously.
fs.symlink(destination, path[, type], callback)
Symlink asynchronously.
fs.rmdir(path, callback)
Renames an existing directory.
fs.mkdir(path[, mode], callback)
Creates a new directory.
fs.readdir(path, callback)
Reads the content of the specified directory.
fs.utimes(path, atime, mtime, callback)
Changes the timestamp of the file.
fs.exists(path, callback)
Determines whether the specified file exists or not.
fs.access(path[, mode], callback)
Tests a user's permissions for the specified file.
fs.appendFile(file, data[, options], callback)
Appends new content to the existing file.
Debug Node.js Application
Core Node.js Debugger
app.js
var fs = require('fs');
fs.readFile('test.txt', 'utf8', function (err, data) {
debugger;
if (err) throw err;
console.log(data);
});
node debug app.js
The following table lists important debugging commands:
Command
Description
next
Stop at the next statement.
cont
Continue execute and stop at the debugger statement if any.
step
Step in function.
out
Step out of function.
watch
Add the expression or variable into watch.
watcher
See the value of all expressions and variables added into watch.
Pause
Pause running code.
Node Inspector
app.js
var fs = require('fs');
fs.readFile('test.txt', 'utf8', function (err, data) {
debugger;
if (err) throw err;
console.log(data);
});
npm install -g node-inspector
D:\>node-inspector --web-port=5500
>node --debug-brk app.js
Node.js EventEmitter
Example: Raise and Handle Node.js events
// get the reference of EventEmitter class of events module
var events = require('events');
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
//Subscribe for FirstEvent
em.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
Example: EventEmitter
var emitter = require('events').EventEmitter;
var em = new emitter();
//Subscribe FirstEvent
em.addListener('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});
//Subscribe SecondEvent
em.on('SecondEvent', function (data) {
console.log('First subscriber: ' + data);
});
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
// Raising SecondEvent
em.emit('SecondEvent', 'This is my second Node.js event emitter example.');
Return EventEmitter from a function
Example: Return EventEmitter from a function
var emitter = require('events').EventEmitter;
function LoopProcessor(num) {
var e = new emitter();
setTimeout(function () {
for (var i = 1; i <= num; i++) {
e.emit('BeforeProcess', i);
console.log('Processing number:' + i);
e.emit('AfterProcess', i);
}
}
, 2000)
return e;
}
var lp = LoopProcessor(3);
lp.on('BeforeProcess', function (data) {
console.log('About to start the process for ' + data);
});
lp.on('AfterProcess', function (data) {
console.log('Completed processing ' + data);
});
Output:
About to start the process for 1
Processing number:1
Completed processing 1
About to start the process for 2
Processing number:2
Completed processing 2
About to start the process for 3
Processing number:3
Completed processing 3
Example: Extend EventEmitter Class
var emitter = require('events').EventEmitter;
var util = require('util');
function LoopProcessor(num) {
var me = this;
setTimeout(function () {
for (var i = 1; i <= num; i++) {
me.emit('BeforeProcess', i);
console.log('Processing number:' + i);
me.emit('AfterProcess', i);
}
}
, 2000)
return this;
}
util.inherits(LoopProcessor, emitter)
var lp = new LoopProcessor(3);
lp.on('BeforeProcess', function (data) {
console.log('About to start the process for ' + data);
});
lp.on('AfterProcess', function (data) {
console.log('Completed processing ' + data);
});
Output:
About to start the process for 1
Processing number:1
Completed processing 1
About to start the process for 2
Processing number:2
Completed processing 2
About to start the process for 3
Processing number:3
Completed processing 3
Frameworks for Node.js
Sl.
Open-Source Framework
Description
1
Express.js
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. This is the most popular framework as of now for Node.js.
2
Geddy
Geddy is a simple, structured web application framework for Node.js based on MVC architecture.
3
Locomotive
Locomotive is MVC web application framework for Node.js. It supports MVC patterns, RESTful routes, and convention over configuration, while integrating seamlessly with any database and template engine. Locomotive builds on Express, preserving the power and simplicity you've come to expect from Node.
4
Koa
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
5
Total.js
Totaljs is free web application framework for building web sites and web applications using JavaScript, HTML and CSS on Node.js
6
Hapi.js
Hapi is a rich Node.js framework for building applications and services.
7
Keystone
Keystone is the open source framework for developing database-driven websites, applications and APIs in Node.js. Built on Express and MongoDB.
8
Derbyjs
Derby support single-page apps that have a full MVC structure, including a model provided by Racer, a template and styles based view, and controller code with application logic and routes.
9
Sails.js
Sails makes it easy to build custom, enterprise-grade Node.js apps. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture. It's especially good for building chat, realtime dashboards, or multiplayer games; but you can use it for any web application project - top to bottom.
10
Meteor
Meteor is a complete open source platform for building web and mobile apps in pure JavaScript.
11
Mojito
This HTML5 framework for the browser and server from Yahoo offers direct MVC access to the server database through the local routines. One clever feature allows the code to migrate. If the client can't run JavaScript for some reason, Mojito will run it on the server -- a convenient way to handle very thin clients.
12
Restify
Restify is a node.js module built specifically to enable you to build correct REST web services.
12
Loopback
Loopback is an open-source Node.js API framework.
13
ActionHero
actionhero.js is a multi-transport Node.JS API Server with integrated cluster capabilities and delayed tasks.
14
Frisby
Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun.
15
Chocolate.js
Chocolate is a simple webapp framework built on Node.js using Coffeescript.
Express.js
Install Express.js
npm install -g express
C:\MyNodeJSApp> npm install express --save
Express.js Web Application
app.js: Express.js Web Server
var express = require('express');
var app = express();
// define routes here..
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
Example: Configure Routes in Express.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('
Hello World
');
});
app.post('/submit-data', function (req, res) {
res.send('POST Request');
});
app.put('/update-data', function (req, res) {
res.send('PUT Request');
});
app.delete('/delete-data', function (req, res) {
res.send('DELETE Request');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
Example: Configure Routes in Express.js
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="/submit-student-data" method="post">
First Name: <input name="firstName" type="text" /> <br />
Last Name: <input name="lastName" type="text" /> <br />
<input type="submit" />
</form>
</body>
</html>
Body Parser
npm install body-parser --save
app.js: Handle POST Route in Express.js
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.sendFile('index.html');
});
app.post('/submit-student-data', function (req, res) {
var name = req.body.firstName + ' ' + req.body.lastName;
res.send(name + ' Submitted Successfully!');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
Serving Static Resources in Node.js
server.js
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public')); //Serves resources from public folder
var server = app.listen(5000);
var express = require('express');
var app = express();
app.use(express.static('public'));
//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));
var server = app.listen(5000);
Example: Setting virtual path
app.use('/resources',express.static(__dirname + '/images'));
npm install node-static
var http = require('http');
var nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(5000);
Total : 26654
Today :3
Today Visit Country :