Nodejs Quick Guide

Embed Size (px)

Citation preview

  • 7/26/2019 Nodejs Quick Guide

    1/76

    http://www.tutorialspoint.com/nodejs/nodejs_quick_guide.htm Copyright tutorialspoint.com

    NODE.JS - QUICK GUIDENODE.JS - QUICK GUIDE

    NODE.JS - INTRODUCTIONNODE.JS - INTRODUCTION

    What is Node.js?

    Node.js is a web application framework built on Google Chrome's JavaScript EngineV8Engine. Its

    latest version is v0.10.36. Defintion of Node.js as put by its official documentationis as follows:

    Node.js is a platform built on Chrome's JavaScript runtimefor easily building fast,scalable network applications. Node.js uses an event-driven, non-blocking I/O modelthat makes it lightweight and efficient, perfect for data-intensive real-timeapplications that run across distributed devices.

    Node.js comes with runtime environment on which a Javascript based script can be interpreted andexecuted ItisanalogustoJVMtoJAVAbytecode. This runtime allows to execute a JavaScript code on anymachine outside a browser. Because of this runtime of Node.js, JavaScript is now can be executedon server as well.

    Node.js also provides a rich library of various javascript modules which eases the developement ofweb application using Node.js to great extents.

    Node.js = Runtime Environment + JavaScript Library

    Features of Node.js

    Aynchronous and Event DrivenAll APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data.Server moves to next API after calling it and a notification mechanism of Events of Node.jshelps server to get response from the previous API call.

    Very FastBeing built on Google Chrome's V8 JavaScript Engine, Node.js library is very fastin code execution.

    Single Threaded but highly Scalable- Node.js uses a single threaded model with eventlooping. Event mechanism helps server to respond in a non-bloking ways and makes serverhighly scalable as opposed to traditional servers which create limited threads to handlerequests. Node.js uses a single threaded program and same program can services muchlarger number of requests than traditional server like Apache HTTP Server.

    No Buffering- Node.js applications never buffer any data. These applications simply outputthe data in chunks.

    License- Node.js is released under the MIT license.

    Who Uses Node.js?Following is the link on github wiki containing an exhaustive list of projects, application andcompanies which are using Node.js. This list include eBay, General Electric, GoDaddy, Microsoft,PayPal, Uber, Wikipins, Yahoo!, Yammer and the list continues.

    Projects, Applications, and Companies Using Node

    Concepts

    The following diagram depicts some important parts of Node.js which we will discuss in detail in thesubsequent chapters.

    https://github.com/joyent/node/wiki/projects,-applications,-and-companies-using-nodehttps://raw.githubusercontent.com/joyent/node/v0.12.0/LICENSEhttp://code.google.com/p/v8/http://code.google.com/p/v8/https://github.com/joyent/node/wiki/projects,-applications,-and-companies-using-nodehttps://raw.githubusercontent.com/joyent/node/v0.12.0/LICENSEhttp://code.google.com/p/v8/http://nodejs.org/http://www.tutorialspoint.com/nodejs/nodejs_quick_guide.htm
  • 7/26/2019 Nodejs Quick Guide

    2/76

    Where to Use Node.js?

    Following are the areas where Node.js is proving itself a perfect technology partner.

    I/O bound Applications

    Data Streaming Applications

    Data Intensive Realtime Applications DIRT

    JSON APIs based Applications

    Single Page Applications

    Where Not to Use Node.js?

    It is not advisable to use Node.js for CPU intensive applications.

    NODE.JS - ENVIRONMENT SETUPNODE.JS - ENVIRONMENT SETUP

    Try it Option Online

    You really do not need to set up your own environment to start learning Node.js. Reason is verysimple, we already have set up Node.js environment online, so that you can compile and execute

    all the available examples online at the same time when you are doing your theory work. Thisgives you confidence in what you are reading and to check the result with different options. Feelfree to modify any example and execute it online.

    Try following example using Try itoption available at the top right corner of the below samplecode box:

    console.log("Hello World!");

    For most of the examples given in this tutorial, you will find Try itoption, so just make use of it andenjoy your learning.

    Local Environment Setup

    If you are still willing to set up your environment for Node.js, you need the following two softwaresavailable on your computer, aText Editor and bThe Node.js binary installables.

    Text Editor

    This will be used to type your program. Examples of few editors include Windows Notepad, OS Editcommand, Brief, Epsilon, EMACS, and vim or vi.

    Name and version of text editor can vary on different operating systems. For example, Notepadwill be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.

    The files you create with your editor are called source files and contain program source code. Thesource files for Node.js programs are typically named with the extension ".js".

    Before starting your programming, make sure you have one text editor in place and you haveenough experience to write a computer program, save it in a file, compile it and finally execute it.

    The Node.js Runtime

  • 7/26/2019 Nodejs Quick Guide

    3/76

    The source code written in source file is simply javascript. The Node.js interprter will be used tointerpret and execute your javascript code.

    Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windowsoperating systems with the 32-bit 386and 64-bit amd64x86 processor architectures.

    Following section guides you on how to install Node.js binary distribution on various OS.

    Download Node.js archive

    Download latest version of Node.js installable archive file from Node.js Downloads. At the time ofwriting this tutorial, I downloaded node-v0.12.0-x64.msiand copied it into C:\>nodejs folder.

    OS Archive name

    Windows node-v0.12.0-x64.msi

    Linux node-v0.12.0-linux-x86.tar.gz

    Mac node-v0.12.0-darwin-x86.tar.gz

    SunOS node-v0.12.0-sunos-x86.tar.gz

    Installation on UNIX/Linux/Mac OS X, and SunOS

    Extract the download archive into /usr/local, creating a NodeJs tree in /usr/local/nodejs. Forexample:

    tar -C /usr/local -xzf node-v0.12.0-linux-x86.tar.gz

    Add /usr/local/nodejs to the PATH environment variable.

    OS Output

    Linux export PATH=$PATH:/usr/local/nodejs

    Mac export PATH=$PATH:/usr/local/nodejs

    FreeBSD export PATH=$PATH:/usr/local/nodejs

    Installation on Windows

    Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses theNode.js distribution in C:\Program Files\nodejs. The installer should set the C:\Program Files\nodejsdirectory in window's PATH environment variable. Restart any open command prompts for thechange to take effect.

    Verify installation: Executing a File

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    console.log("Hello World")

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output

    Hello, World!

    NODE.JS - FIRST APPLICATIONNODE.JS - FIRST APPLICATION

    http://nodejs.org/download/
  • 7/26/2019 Nodejs Quick Guide

    4/76

    Before creating actual Hello World ! application using Node.js, let us see the parts of a Node.jsapplication. A Node.js application consists of following three important parts:

    import required module: use require directive to load a javascript module

    create server:A server which will listen to client's request similar to Apache HTTP Server.

    read request and return response:server created in earlier step will read HTTP requestmade by client which can be a browser or console and return the response.

    Creating Node.js Application

    Step 1: import required module

    use require directive to load http module.

    varhttp =require("http")

    Step 2: create an HTTP server using http.createServer method. Pass it a function with parametersrequest and response. Write the sample implementation to always return "Hello World". Pass aport 8081 to listen method.

    http.createServer(function(request,response){ // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200,{'Content-Type':'text/plain'}); // send the response body as "Hello World" response.end('Hello World\n');}).listen(8081);// console will print the message

    console.log('Server running at http://127.0.0.1:8081/');

    Step 3: Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varhttp =require("http")

    http.createServer(function(request,response){response.writeHead(200,{'Content-Type':'text/plain'});response.end('Hello World\n');

    }).listen(8081);console.log('Server running at http://127.0.0.1:8081/');

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output. Server has started

    Server running at http://127.0.0.1:8081/

    Make a request to Node.js server

    Open http://127.0.0.1:8081/ in any browser and see the below result.

  • 7/26/2019 Nodejs Quick Guide

    5/76

    NODE.JS - REPLNODE.JS - REPL

    REPL stands for Read Eval Print Loop and it represents a computer environment like a windowconsole or unix/linux shell where a command is entered and system responds with an output.Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.

    Read- Reads user's input, parse the input into JavaScript data-structure and stores inmemory.

    Eval- Takes and evaluates the data structure

    Print- Prints the result

    Loop- Loops the above command until user press ctrl-c twice.

    REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript

    codes.

    Features

    REPL can be started by simply running node on shell/console without any argument.

    C:\Nodejs_WorkSpace> node

    You will see the REPL Command prompt:

    C:\Nodejs_WorkSpace> node>

    Simple Expression

    Let's try simple mathematics at REPL command prompt:

    C:\Nodejs_WorkSpace>node> 1 + 34> 1 + ( 2 * 3 ) - 4

    3>

    Use variables

    Use variables to store values and print later. if var keyword is not used then value is stored in thevariable and printed. Wheras if var keyword is used then value is stored but not printed. You canuse both variables later. Print anything usind console.log

    C:\Nodejs_WorkSpace> node> x = 1010> var y = 10

    undefined> x + y20> console.log("Hello World")Hello Workdundefined

    Multiline Expression

    Node REPL supports multiline expression similar to JavaScript. See the following do-while loop in

  • 7/26/2019 Nodejs Quick Guide

    6/76

    action:

    C:\Nodejs_WorkSpace> node> var x = 0undefined> do {... x++;... console.log("x: " + x);... } while ( x < 5 );x: 1x: 2

    x: 3x: 4x: 5undefined>

    ...comes automatically when you press enters after opening bracket. Node automatically checksthe continuity of expressions.

    Underscore variable

    Use _to get the last result.

    C:\Nodejs_WorkSpace>node> var x = 10undefined

    > var y = 20undefined> x + y30> var sum = _undefined> console.log(sum)30undefined>

    REPL Commands

    ctrl + c- terminate the current command.

    ctrl + c twice- terminate the Node REPL.

    ctrl + d- terminate the Node REPL.

    Up/Down Keys- see command history and modify previous commands.

    tab Keys- list of current commands.

    .help- list of all commands.

    .break- exit from multiline expression.

    .clear- exit from multiline expression

    .save- save current Node REPL session to a file.

    .load- load file content in current Node REPL session.

    C:\Nodejs_WorkSpace>node> var x = 10undefined> var y = 20undefined

    > x + y30> var sum = _undefined> console.log(sum)30

    undefined

  • 7/26/2019 Nodejs Quick Guide

    7/76

    > .save test.jsSession saved to:test.js> .load test.js> var x = 10undefined> var y = 20undefined

    > x + y30> var sum = _undefined

    > console.log(sum)30undefined>

    NODE.JS - NPMNODE.JS - NPM

    npm stands for Node Package Manager. npm provides following two main functionalities:

    Online repositories for node.js packages/modules which are searchable on search.nodejs.org

    Command line utility to install packages, do version management and dependencymanagement of Node.js packages.

    npm comes bundled with Node.js installables after v0.6.3 version. To verify the same, openconsole and type following command and see the result:

    C:\Nodejs_WorkSpace>npm --version2.5.1

    Global vs Local installation

    By default, npm installs any dependency in the local mode. Here local mode refers to the packageinstallation in node_modules directory lying in the folder where Node application is present.Locally deployed packages are accessible via require.

    Globally installed packages/dependencies are stored in /npm directory. Such

    dependencies can be used in CLI CommandLineInterfacefunction of any node.js but can not beimported using require in Node application directly.

    Let's install express, a popular web framework using local installation.

    C:\Nodejs_WorkSpace>npm install [email protected] node_modules\express|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]

    |-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]|-- [email protected]

    |-- [email protected] ([email protected])|-- [email protected] ([email protected], [email protected], [email protected])|-- [email protected] ([email protected])|-- [email protected] ([email protected])

    |-- [email protected] ([email protected], [email protected])|-- [email protected] ([email protected])|-- [email protected] ([email protected], [email protected])

    Once npm completes the download, you can verify by looking at the content ofC:\Nodejs_WorkSpace\node_modules. Or type the following command:

    http://search.nodejs.org/
  • 7/26/2019 Nodejs Quick Guide

    8/76

    C:\Nodejs_WorkSpace>npm lsC:\Nodejs_WorkSpace|-- [email protected] |-- [email protected] | |-- [email protected] | | |-- [email protected] | |-- [email protected]

    |-- [email protected] |-- [email protected] |-- [email protected]

    |-- [email protected] | |-- [email protected] |-- [email protected] |-- [email protected] |-- [email protected] | |-- [email protected] |-- [email protected] |-- [email protected]

    |-- [email protected] |-- [email protected] |-- [email protected] |-- [email protected] | |-- [email protected] |-- [email protected] |-- [email protected] |-- [email protected] | |-- [email protected] | |-- [email protected]

    |-- [email protected] |-- [email protected] |-- [email protected] | |-- [email protected] | |-- [email protected] | |-- [email protected] |-- [email protected] |-- [email protected] | |-- [email protected] | |-- [email protected] |-- [email protected]

    |-- [email protected]

    Now Let's try installing express, a popular web framework using global installation.

    C:\Nodejs_WorkSpace>npm install express - g

    Once npm completes the download, you can verify by looking at the content of /npm/node_modules. Or type the following command:

    C:\Nodejs_WorkSpace>npm ls -g

    Installing a module

    Installation of any module is as simple as typing the following command.

    C:\Nodejs_WorkSpace>npm install express

    Now you can use it in your js file as following:

    varexpress =require('express');

    Using package.json

    package.json is present in the root directoryt of any Node application/module and is used to define

    the properties of a package. Let's open package.json of express package present inC:\Nodejs_Workspace\node_modules\express\

    { "name":"express", "description":"Fast, unopinionated, minimalist web framework", "version":"4.11.2",

  • 7/26/2019 Nodejs Quick Guide

    9/76

    "author":{ "name":"TJ Holowaychuk", "email":"[email protected]" }, "contributors":[ { "name":"Aaron Heckmann",

    "email":"[email protected]" }, { "name":"Ciaran Jessup",

    "email":"[email protected]" }, { "name":"Douglas Christopher Wilson", "email":"[email protected]" }, {

    "name":"Guillermo Rauch", "email":"[email protected]" }, { "name":"Jonathan Ong", "email":"[email protected]" },

    { "name":"Roman Shtylman", "email":"[email protected]"

    }, { "name":"Young Jae Sim", "email":"[email protected]" } ], "license":"MIT", "repository":{ "type":"git", "url":"https://github.com/strongloop/express" },

    "homepage":"http://expressjs.com/", "keywords":[ "express", "framework", "sinatra", "web", "rest", "restful", "router", "app",

    "api" ], "dependencies":{ "accepts":"~1.2.3", "content-disposition":"0.5.0",

    "cookie-signature":"1.0.5", "debug":"~2.1.1", "depd":"~1.0.0", "escape-html":"1.0.1", "etag":"~1.5.1", "finalhandler":"0.3.3",

    "fresh":"0.2.4", "media-typer":"0.3.0", "methods":"~1.1.1", "on-finished":"~2.2.0", "parseurl":"~1.3.0", "path-to-regexp":"0.1.3", "proxy-addr":"~1.0.6", "qs":"2.3.3",

    "range-parser":"~1.0.2", "send":"0.11.1",

    "serve-static":"~1.8.1", "type-is":"~1.5.6", "vary":"~1.0.0", "cookie":"0.1.2", "merge-descriptors":"0.0.2",

  • 7/26/2019 Nodejs Quick Guide

    10/76

    "utils-merge":"1.0.0" }, "devDependencies":{ "after":"0.8.1", "ejs":"2.1.4", "istanbul":"0.3.5", "marked":"0.3.3",

    "mocha":"~2.1.0", "should":"~4.6.2", "supertest":"~0.15.0", "hjs":"~0.0.6",

    "body-parser":"~1.11.0", "connect-redis":"~2.2.0", "cookie-parser":"~1.3.3", "express-session":"~1.10.2", "jade":"~1.9.1", "method-override":"~2.3.1", "morgan":"~1.5.1",

    "multiparty":"~4.1.1", "vhost":"~3.0.0" }, "engines":{ "node":">= 0.10.0" }, "files":[

    "LICENSE", "History.md", "Readme.md",

    "index.js", "lib/" ], "scripts":{ "test":"mocha --require test/support/env --reporter spec --bail --check-leaks test/test/acceptance/", "test-cov":"istanbul cover node_modules/mocha/bin/_mocha -- --requiretest/support/env --reporter dot --check-leaks test/ test/acceptance/", "test-tap":"mocha --require test/support/env --reporter tap --check-leaks test/test/acceptance/", "test-travis":"istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --

    require test/support/env --reporter spec --check-leaks test/ test/acceptance/" }, "gitHead":"63ab25579bda70b4927a179b580a9c580b6c7ada", "bugs":{ "url":"https://github.com/strongloop/express/issues" }, "_id":"[email protected]", "_shasum":"8df3d5a9ac848585f00a0777601823faecd3b148", "_from":"express@*", "_npmVersion":"1.4.28",

    "_npmUser":{ "name":"dougwilson", "email":"[email protected]" }, "maintainers":[

    { "name":"tjholowaychuk", "email":"[email protected]" }, { "name":"jongleberry",

    "email":"[email protected]" }, { "name":"shtylman", "email":"[email protected]" }, { "name":"dougwilson",

    "email":"[email protected]" },

    { "name":"aredridel", "email":"[email protected]" }, {

  • 7/26/2019 Nodejs Quick Guide

    11/76

    "name":"strongloop", "email":"[email protected]" }, { "name":"rfeng", "email":"[email protected]" }

    ], "dist":{ "shasum":"8df3d5a9ac848585f00a0777601823faecd3b148", "tarball":"http://registry.npmjs.org/express/-/express-4.11.2.tgz"

    }, "directories":{}, "_resolved":"https://registry.npmjs.org/express/-/express-4.11.2.tgz" , "readme":"ERROR: No README data found!"}

    Attributes of Package.json

    name- name of the package

    version- version of the package

    description- description of the package

    homepage- homepage of the package

    author- author of the package

    contributors- name of the contributors to the package

    dependencies- list of dependencies. npm automatically installs all the dependenciesmentioned here in the node_module folder of the package.

    repository- repository type and url of the package

    main- entry point of the package

    keywords- keywords

    Uninstalling a module

    Use following command to uninstall a module.

    C:\Nodejs_WorkSpace>npm uninstall express

    Once npm uninstall the package, you can verify by looking at the content of /npm/node_modules. Or type the following command:

    C:\Nodejs_WorkSpace>npm ls

    Updating a moduleUpdate package.json and change the version of the dependency which to be updated and run thefollowing command.

    C:\Nodejs_WorkSpace>npm update

    Search a module

    Search package name using npm.

    C:\Nodejs_WorkSpace>npm search express

    Create a module

    Creation of module requires package.json to be generated. Let's generate package.json usingnpm.

    C:\Nodejs_WorkSpace>npm init

  • 7/26/2019 Nodejs Quick Guide

    12/76

    This utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sane defaults.

    See 'npm help json' for definitive documentation on these fieldsand exactly what they do.

    Use 'npm install --save' afterwards to install a package and

    save it as a dependency in the package.json file.

    Press ^C at any time to quit.name: (Nodejs_WorkSpace)

    Once package.json is generated. Use following command to register yourself with npm repositorysite using a valid email address.

    C:\Nodejs_WorkSpace>npm adduser

    Now its time to publish your module:

    C:\Nodejs_WorkSpace>npm publish

    NODE.JS - CALLBACKS CONCEPTNODE.JS - CALLBACKS CONCEPT

    What is Callback?Callback is an asynchronous equivalent for a function. A callback function is called at thecompletion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is sucha way that they supports callbacks. For example, a function to read a file may start reading file andreturn the control to execution environment immidiately so that next instruction can be executed.Once file I/O is complete, it will call the callback function while passing the callback function, thecontent of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.jshighly scalable, as it can process high number of request without waiting for any function to returnresult.

    Blocking Code Example

    Create a txt file named test.txt in C:\>Nodejs_WorkSpace

    TutorialsPoint.Com

    Create a js file named test.js in C:\>Nodejs_WorkSpace

    varfs =require("fs");vardata =fs.readFileSync('test.txt');console.log(data.toString());

    console.log("Program Ended");

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output

    TutorialsPoint.ComProgram Ended

    Non-Blocking Code Example

    Create a txt file named test.txt in C:\>Nodejs_WorkSpace

    TutorialsPoint.Com

    Update test.js in C:\>Nodejs_WorkSpace

    varfs =require("fs");

    fs.readFile('test.txt',function(err,data){ if(err)returnconsole.error(err);

  • 7/26/2019 Nodejs Quick Guide

    13/76

  • 7/26/2019 Nodejs Quick Guide

    14/76

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output. Server has started

    connection succesful.data received succesfully.Program Ended.

    How Node Applications Work?

    In Node Application, any async function accepts a callback as a last parameter and the callbackfunction accepts error as a first parameter. Let's revisit the previous example again.

    varfs =require("fs");

    fs.readFile('test.txt',function(err,data){ if(err){ console.log(err.stack); return;} console.log(data.toString());

    });console.log("Program Ended");

    Here fs.readFile is a async function whose purpose is to read a file. If an error occur during read offile, then err object will contain the corresponding error else data will contain the contents of thefile. readFile passes err and data to callback function after file read operation is complete.

    NODE.JS - EVENT EMITTERNODE.JS - EVENT EMITTER

    EventEmitter class lies in eventsmodule. It is accessibly via following syntax:

    //import events module

    varevents =require('events');//create an eventEmitter objectvareventEmitter =newevents.EventEmitter();

    When an EventEmitter instance faces any error, it emits an 'error' event. When new listener isadded, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.

    EventEmitter provides multiple properties like onand emit. onproperty is used to bind a functionwith the event and emitis used to fire an event.

    Methods

    Sr.No.

    method Description

    1 addListenerevent, listener

    Adds a listener to the end of the listeners array for the specifiedevent. No checks are made to see if the listener has already beenadded. Multiple calls passing the same combination of event andlistener will result in the listener being added multiple times.Returns emitter, so calls can be chained.

    2 onevent, listener Adds a listener to the end of the listeners array for the specifiedevent. No checks are made to see if the listener has already beenadded. Multiple calls passing the same combination of event andlistener will result in the listener being added multiple times.Returns emitter, so calls can be chained.

    3 onceevent, listener Adds a one time listener for the event. This listener is invokedonly the next time the event is fired, after which it is removed.Returns emitter, so calls can be chained.

    4 removeListener Remove a listener from the listener array for the specified event.

  • 7/26/2019 Nodejs Quick Guide

    15/76

    event, listener Caution: changes array indices in the listener array behind thelistener. removeListener will remove, at most, one instance of alistener from the listener array. If any single listener has beenadded multiple times to the listener array for the specified event,then removeListener must be called multiple times to removeeach instance. Returns emitter, so calls can be chained.

    5 removeAllListeners[event]

    Removes all listeners, or those of the specified event. It's not agood idea to remove listeners that were added elsewhere in thecode, especially when it's on an emitter that you didn't create

    e.g.socketsorfilestreams. Returns emitter, so calls can be chained.

    6 setMaxListenersn By default EventEmitters will print a warning if more than 10listeners are added for a particular event. This is a useful defaultwhich helps finding memory leaks. Obviously not all Emittersshould be limited to 10. This function allows that to be increased.Set to zero for unlimited.

    7 listenersevent Returns an array of listeners for the specified event.

    8 emitevent, [ arg1], [arg2], [. . . ]

    Execute each of the listeners in order with the suppliedarguments. Returns true if event had listeners, false otherwise.

    Class Methods

    Sr. No. method Description

    1 listenerCountemitter,event Return the number of listeners for a given event.

    Events

    Sr.

    No.

    event name Parameters Description

    1 newListenerevent-StringTheeventname

    listener-FunctionThe

    eventhandlerfunction

    This event is emitted any time a listener is added.When this event is triggered, the listener may not yethave been added to the array of listeners for theevent.

    2 removeListenerevent-StringTheeventname

    listener-

    FunctionTheeventhandlerfunction

    This event is emitted any time someone removes alistener. When this event is triggered, the listenermay not yet have been removed from the array oflisteners for the event.

  • 7/26/2019 Nodejs Quick Guide

    16/76

    Example

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varevents =require('events');vareventEmitter =newevents.EventEmitter();

    //listener #1varlistner1 =functionlistner1(){ console.log('listner1 executed.');}

    //listener #2varlistner2 =functionlistner2(){ console.log('listner2 executed.');}

    // bind the connection event with the listner1 functioneventEmitter.addListener('connection',listner1);

    // bind the connection event with the listner2 functioneventEmitter.on('connection',listner2);

    vareventListeners =require('events').EventEmitter.listenerCount(eventEmitter,'connection');console.log(eventListeners +" Listner(s) listening to connection event");

    // fire the connection eventeventEmitter.emit('connection');

    // remove the binding of listner1 functioneventEmitter.removeListener('connection',listner1);console.log("Listner1 will not listen now.");

    // fire the connection eventeventEmitter.emit('connection');

    eventListeners =require('events').EventEmitter.listenerCount(eventEmitter,'connection');console.log(eventListeners +" Listner(s) listening to connection event");

    console.log("Program Ended.");

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output. Server has started

    2 Listner(s) listening to connection eventlistner1 executed.listner2 executed.Listner1 will not listen now.listner2 executed.1 Listner(s) listening to connection event

    Program Ended.

    NODE.JS - BUFFER MODULENODE.JS - BUFFER MODULE

    buffermodule can be used to create Buffer and SlowBuffer classes. Buffer module can beimported using following syntax.

    varbuffer =require("buffer")

    Buffer class

    Buffer class is a global class and can be accessed in application without importing buffer module.A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside theV8 heap. A Buffer cannot be resized.

  • 7/26/2019 Nodejs Quick Guide

    17/76

    Methods

    Sr.No.

    method Parameters Description

    1 new Buffersizesize Number

    Allocates a new bufferof size octets. Note,size must be no more

    than kMaxLength.Otherwise, aRangeError will bethrown here.

    2 new Bufferbufferbuffer Buffer

    Copies the passedbuffer data onto anew Buffer instance.

    3 new Bufferstr[, encoding]str String -string toencode.

    encodingString -encoding touse,Optional.

    Allocates a new buffercontaining the givenstr. encoding defaultsto 'utf8'.

    4 buf.length Return: Number The size of the bufferin bytes. Note that thisis not necessarily thesize of the contents.length refers to theamount of memoryallocated for thebuffer object. It doesnot change when thecontents of the bufferare changed.

    5 buf.writestring[,offset][, length][, encoding]string String- data to bewritten tobuffer

    offsetNumber,

    Optional,Default: 0

    lengthNumber,Optional,Default:buffer.length- offset

    encodingString,Optional,Default:

    'utf8'

    Allocates a new buffercontaining the givenstr. encoding defaultsto 'utf8'.

    6 buf.writeUIntLEvalue,offset,byteLength[,noAssert] value

    {Number}

    Writes value to thebuffer at the specifiedoffset and byteLength.

  • 7/26/2019 Nodejs Quick Guide

    18/76

    Bytes to bewritten tobuffer

    offset{Number} 0

  • 7/26/2019 Nodejs Quick Guide

    19/76

    noAssert{Boolean}Default:false

    Return:{Number}

    9 buf.writeIntBEvalue,offset,byteLength[,noAssert] value

    {Number}Bytes to bewritten tobuffer

    offset{Number} 0

  • 7/26/2019 Nodejs Quick Guide

    20/76

    noAssert{Boolean}Default:false

    Return:{Number}

    12 buf.readIntLEoffset,byteLength[,noAssert]offset{Number} 0

  • 7/26/2019 Nodejs Quick Guide

    21/76

    representation of theBuffer instance.JSON.stringifyimplicitly calls thisfunction whenstringifying a Bufferinstance.

    16 buf[index] Get and set the octetat index. The values

    refer to individualbytes, so the legalrange is between0x00 and 0xFF hex or0 and 255.

    17 buf.equalsotherBufferotherBufferBuffer

    Returns a boolean ofwhether this andotherBuffer have thesame bytes.

    18 buf.compareotherBufferotherBufferBuffer

    Returns a numberindicating whetherthis comes before or

    after or is the same asthe otherBuffer in sortorder.

    19 buf.copytargetBuffer[, targetStart][, sourceStart][, sourceEnd] targetBuffer

    Buffer object- Buffer tocopy into

    targetStartNumber,Optional,

    Default: 0sourceStartNumber,Optional,Default: 0

    sourceEndNumber,Optional,Default:buffer.length

    Copies data from aregion of this buffer toa region in the targetbuffer even if thetarget memory regionoverlaps with thesource. If undefinedthe targetStart andsourceStart

    parameters default to0 while sourceEnddefaults tobuffer.length.

    20 buf.slice[start][, end] startNumber,Optional,Default: 0

    end Number,Optional,Default:buffer.length

    Returns a new bufferwhich references thesame memory as theold, but offset andcropped by the startdefaultsto0and enddefaultstobuffer.length

    indexes. Negativeindexes start from theend of the buffer.

    21 buf.readUInt8offset[,noAssert]offset

    Number

    noAssertBoolean,Optional,Default:

    Reads an unsigned 8bit integer from the

    buffer at the specifiedoffset. Set noAssert totrue to skip validationof offset. This meansthat offset may bebeyond the end of the

  • 7/26/2019 Nodejs Quick Guide

    22/76

    a se

    Return:Number

    buffer. Defaults tofalse.

    22 buf.readUInt16LEoffset[,noAssert]offsetNumber

    noAssert

    Boolean,Optional,Default:false

    Return:Number

    Reads an unsigned 16bit integer from thebuffer at the specifiedoffset with specifiedendian format. Set

    noAssert to true toskip validation ofoffset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    23 buf.readUInt16BEoffset[,noAssert]offsetNumber

    noAssert

    Boolean,Optional,Default:false

    Return:Number

    Reads an unsigned 16bit integer from thebuffer at the specifiedoffset with specifiedendian format. Set

    noAssert to true toskip validation ofoffset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    24 buf.readUInt32LEoffset[,noAssert]offsetNumber

    noAssert

    Boolean,Optional,Default:false

    Return:Number

    Reads an unsigned 32bit integer from thebuffer at the specifiedoffset with specifiedendian format. SetnoAssert to true toskip validation ofoffset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    25 buf.readUInt32BEoffset[,noAssert]offsetNumber

    noAssert

    Boolean,Optional,Default:false

    Return:Number

    Reads an unsigned 32bit integer from thebuffer at the specifiedoffset with specifiedendian format. SetnoAssert to true toskip validation ofoffset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    26 buf.readInt8offset[,noAssert]offsetNumber

    noAssertBoolean,Optional,Default:false

    Return:

    Reads a signed 8 bitinteger from thebuffer at the specifiedoffset. Set noAssert to

    true to skip validationof offset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

  • 7/26/2019 Nodejs Quick Guide

    23/76

    Number

    27 buf.readInt16LEoffset[,noAssert]offsetNumber

    noAssertBoolean,Optional,Default:false

    Return:Number

    Reads a signed 16 bitinteger from thebuffer at the specifiedoffset with specifiedendian format. SetnoAssert to true toskip validation of

    offset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    28 buf.readInt16BEoffset[,noAssert]offsetNumber

    noAssertBoolean,Optional,Default:false

    Return:Number

    Reads a signed 16 bitinteger from thebuffer at the specifiedoffset with specifiedendian format. SetnoAssert to true toskip validation of

    offset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    29 buf.readInt32LEoffset[,noAssert]offsetNumber

    noAssertBoolean,Optional,Default:false

    Return:Number

    Reads a signed 32 bitinteger from thebuffer at the specifiedoffset with specifiedendian format. SetnoAssert to true toskip validation of

    offset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    30 buf.readInt32BEoffset[,noAssert]offsetNumber

    noAssertBoolean,Optional,

    Default:false

    Return:Number

    Reads a signed 32 bitinteger from thebuffer at the specifiedoffset with specifiedendian format. SetnoAssert to true toskip validation of

    offset. This meansthat offset may bebeyond the end of thebuffer. Defaults tofalse.

    31 buf.readFloatLEoffset[, noAssert]offsetNumber

    noAssertBoolean,Optional,

    Default:false

    Return:Number

    Reads a 32 bit floatfrom the buffer at thespecified offset withspecified endianformat. Set noAssertto true to skipvalidation of offset.

    This means that offsetmay be beyond theend of the buffer.Defaults to false.

  • 7/26/2019 Nodejs Quick Guide

    24/76

    32 buf.readFloatBEoffset[,noAssert]offsetNumber

    noAssertBoolean,Optional,Default:false

    Return:Number

    Reads a 32 bit floatfrom the buffer at thespecified offset withspecified endianformat. Set noAssertto true to skipvalidation of offset.This means that offsetmay be beyond theend of the buffer.

    Defaults to false.

    33 buf.readDoubleLEoffset[, noAssert]offsetNumber

    noAssertBoolean,Optional,Default:false

    Return:Number

    Reads a 64 bit doublefrom the buffer at thespecified offset withspecified endianformat. Set noAssertto true to skipvalidation of offset.This means that offsetmay be beyond theend of the buffer.

    Defaults to false.

    34 buf.readDoubleBEoffset[,noAssert]offsetNumber

    noAssertBoolean,Optional,Default:false

    Return:Number

    Reads a 64 bit doublefrom the buffer at thespecified offset withspecified endianformat. Set noAssertto true to skipvalidation of offset.This means that offsetmay be beyond theend of the buffer.

    Defaults to false.

    35 buf.writeUInt8value,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,

    Default:false

    Writes value to thebuffer at the specifiedoffset. Note, valuemust be a validunsigned 8 bit integer.Set noAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for the

    specific function andoffset may be beyondthe end of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    36 buf.writeUInt16LEvalue,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,

    Writes value to thebuffer at the specified

    offset with specifiedendian format. Note,value must be a validunsigned 16 bitinteger. Set noAssertto true to skipvalidation of value

  • 7/26/2019 Nodejs Quick Guide

    25/76

    ,Default:false

    and offset. This meansthat value may be toolarge for the specificfunction and offsetmay be beyond theend of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unless

    you are certain ofcorrectness. Defaultsto false.

    37 buf.writeUInt16BEvalue,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,

    Default:false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a validunsigned 16 bitinteger. Set noAssertto true to skipvalidation of valueand offset. This meansthat value may be toolarge for the specificfunction and offsetmay be beyond theend of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    38 buf.writeUInt32LEvalue,offset[,noAssert] valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a validunsigned 32 bitinteger. Set noAssertto true to skipvalidation of valueand offset. This meansthat value may be toolarge for the specificfunction and offset

    may be beyond theend of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    39 buf.writeUInt32BEvalue,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,

    value must be a validunsigned 32 bitinteger. Set noAssertto true to skipvalidation of valueand offset. This means

  • 7/26/2019 Nodejs Quick Guide

    26/76

    falsethat value may be toolarge for the specificfunction and offsetmay be beyond theend of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain of

    correctness. Defaultsto false.

    40 buf.writeInt8value,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:

    false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a validsigned 8 bit integer.Set noAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for thespecific function andoffset may be beyondthe end of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    41 buf.writeInt16LEvalue,offset[,noAssert]value

    Number

    offsetNumber

    noAssertBoolean,Optional,Default:false

    Writes value to thebuffer at the specified

    offset with specifiedendian format. Note,value must be a validsigned 16 bit integer.Set noAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for thespecific function andoffset may be beyondthe end of the bufferleading to the values

    being silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    42 buf.writeInt16BEvalue,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a validsigned 16 bit integer.Set noAssert to true to

    skip validation ofvalue and offset. Thismeans that value maybe too large for thespecific function andoffset may be beyond

  • 7/26/2019 Nodejs Quick Guide

    27/76

    the end of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    43 buf.writeInt32LEvalue,offset[,noAssert]

    valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:false

    Writes value to the

    buffer at the specifiedoffset with specifiedendian format. Note,value must be a validsigned 32 bit integer.Set noAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for thespecific function andoffset may be beyondthe end of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    44 buf.writeInt32BEvalue,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a validsigned 32 bit integer.

    Set noAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for thespecific function andoffset may be beyondthe end of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain of

    correctness. Defaultsto false.

    45 buf.writeFloatLEvalue,offset[, noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:

    false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a valid32 bit float. SetnoAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for the

    specific function andoffset may be beyondthe end of the bufferleading to the valuesbeing silentlydropped. This should

  • 7/26/2019 Nodejs Quick Guide

    28/76

    not be used unlessyou are certain ofcorrectness. Defaultsto false.

    46 buf.writeFloatBEvalue,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a valid

    32 bit float. SetnoAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for thespecific function andoffset may be beyondthe end of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    47 buf.writeDoubleLEvalue,offset[, noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,

    Default:false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a valid64 bit double. SetnoAssert to true toskip validation ofvalue and offset. Thismeans that value may

    be too large for thespecific function andoffset may be beyondthe end of the bufferleading to the valuesbeing silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

    48 buf.writeDoubleBEvalue,offset[,noAssert]valueNumber

    offsetNumber

    noAssertBoolean,Optional,Default:false

    Writes value to thebuffer at the specifiedoffset with specifiedendian format. Note,value must be a valid64 bit double. SetnoAssert to true toskip validation ofvalue and offset. Thismeans that value maybe too large for thespecific function andoffset may be beyondthe end of the bufferleading to the values

    being silentlydropped. This shouldnot be used unlessyou are certain ofcorrectness. Defaultsto false.

  • 7/26/2019 Nodejs Quick Guide

    29/76

    49 buf.fillvalue[,offset][, end]valueNumber

    offsetNumber,Optional

    end Number,Optional

    Fills the buffer withthe specified value. Ifthe offset defaultsto0and enddefaultstobuffer.lengtharenot given it will fill theentire buffer.

    Class Methods

    Sr.No.

    method Parameters Description

    1 Buffer.isEncodingencoding encoding

    String Theencoding

    string to test

    Returns true if the encoding is a validencoding argument, or false otherwise.

    2 Buffer.isBufferobjobj Object

    Return:Boolean

    Tests if obj is a Buffer.

    3 Buffer.byteLengthstring[,encoding] string String

    encodingString,Optional,Default: 'utf8'

    Return:Number

    Gives the actual byte length of a string.encoding defaults to 'utf8'. This is not thesame as String.prototype.length since thatreturns the number of characters in a string.

    4 Buffer.concatlist[,totalLength] list Array List

    of Bufferobjects toconcat

    totalLengthNumber Totallength of thebuffers whenconcatenated

    Returns a buffer which is the result ofconcatenating all the buffers in the listtogether.

    5 Buffer.comparebuf1,buf2 buf1 Buffer

    buf2 Buffer

    The same as buf1.comparebuf2. Useful forsorting an Array of Buffers.

    Example

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

  • 7/26/2019 Nodejs Quick Guide

    30/76

    //create a buffervarbuffer =newBuffer(26);console.log("buffer length: "+buffer.length);

    //write to buffervardata ="TutorialsPoint.com";buffer.write(data);

    console.log(data +": "+data.length +" characters, "+Buffer.byteLength(data,'utf8')+" bytes");

    //slicing a buffer

    varbuffer1 =buffer.slice(0,14);console.log("buffer1 length: "+buffer1.length);console.log("buffer1 content: "+buffer1.toString());

    //modify buffer by indexesfor(vari =0;i node test.js

    Verify the Output.

    buffer length: 26TutorialsPoint.com: 18 characters, 18 bytes

  • 7/26/2019 Nodejs Quick Guide

    31/76

    buffer1 length: 14buffer1 content: TutorialsPointbuffer content: abcdefghijklmnopqrstuvwxyz772102710598964

    902616931

    buffer4 content: abcdefghijklmnopqrstuvwxyzbuffer5 content: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz

    NODE.JS - STREAMSNODE.JS - STREAMS

    What are Streams?

    Streams are objects that let yu read data from a source or write data to destination in continousfashion. In Node, there are four types of streams.

    Readable- Stream which is used for read operation.

    Writable- Stream which is used for write operation.

    Duplex- Stream which can be used for both read and write operation.

    Transform- A type of duplex stream where the output is computed based on input.

    Each type of Stream is an EventEmitter and throws several events at times. For example, some ofthe commonly used events are:

    data- This event is fired when there is data is available to read.

    end- This event is fired when there is no more data to read.

    error- This event is fired when there is any error receiving or writing data.

    finish- This event is fired when all data has been flushed to underlying system

    Reading from stream

    Create a txt file named test.txt in C:\>Nodejs_WorkSpace

    TutorialsPoint.Com

    Create test.js in C:\>Nodejs_WorkSpace

    varfs =require("fs");vardata ='';//create a readable streamvarreaderStream =fs.createReadStream ('test.txt');

    //set the encoding to be utf8.readerStream.setEncoding('UTF8');

    //handle stream eventsreaderStream.on('data',function(chunk){ data +=chunk;});

    readerStream.on('end',function(){

    console.log(data);});

    readerStream.on('error',function(err){

    console.log(err.stack);});console.log("Program Ended");

    Now run the test.js to see the result:

  • 7/26/2019 Nodejs Quick Guide

    32/76

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output

    Program EndedTutorialsPoint.Com

    Writing to stream

    Update test.js in C:\>Nodejs_WorkSpace

    varfs =require("fs");vardata ='TutorialsPoint.Com';//create a writable streamvarwriterStream =fs.createWriteStream('test1.txt');

    //write the data to stream//set the encoding to be utf8.writerStream.write(data,'UTF8');

    //mark the end of filewriterStream.end();

    //handle stream eventswriterStream.on('finish',function(){ console.log("Write completed.");});

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

    });console.log("Program Ended");

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output

    Program Ended

    Write completed.

    Open test1.txt in C:\>Nodejs_WorkSpace.Verify the result.

    TutorialsPoint.Com

    Piping streams

    Piping is a mechanism to connect output of one stream to another stream. It is normally used to

    get data from one stream and to pass output of that stream to another stream. There is no limit onpiping operations. Consider the above example, where we've read test.txt using readerStream andwrite test1.txt using writerStream. Now we'll use the piping to simplify our operation or readingfrom one file and writing to another file.

    Update test.js in C:\>Nodejs_WorkSpace

    varfs =require("fs");

    //create a readable streamvarreaderStream =fs.createReadStream ('test.txt');

    //create a writable stream

    varwriterStream =fs.createWriteStream('test2.txt');

    //pipe the read and write operations//read test.txt and write data to test2.txtreaderStream.pipe(writerStream);

    console.log("Program Ended");

  • 7/26/2019 Nodejs Quick Guide

    33/76

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output

    Program Ended

    Open test2.txt in C:\>Nodejs_WorkSpace. Verify the result.

    TutorialsPoint.Com

    NODE.JS - FILE SYSTEMNODE.JS - FILE SYSTEM

    fsmodule is used for File I/O. fs module can be imported using following syntax.

    varfs =require("fs")

    Synchronous vs Asynchronous

    Every method in fs module have synchronous as well as asynchronous form. Asynchronous

    methods takes a last parameter as completion function callback and first parameter of thecallback function is error. It is preferred to use asynchronous method instead of synchronousmethod as former never block the program execution where the latter one does.

    Example

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varfs =require("fs");

    //Asynchronous readfs.readFile('test.txt',function(err,data){ if(err)returnconsole.error(err); console.log("Asynchronous read: "+data.toString());

    });

    //Synchronous readvardata =fs.readFileSync('test.txt');console.log("Synchronous read: "+data.toString());

    console.log("Program Ended");

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output.

    Synchronous read: TutorialsPoint.ComProgram EndedAsynchronous read: TutorialsPoint.Com

    Methods

    Sr.No.

    method Description

    1 fs.renameoldPath,newPath,callback Asynchronous rename. No arguments other than apossible exception are given to the completioncallback.

    2 fs.ftruncatefd,len,callback Asynchronous ftruncate. No arguments other thana possible exception are given to the completion

  • 7/26/2019 Nodejs Quick Guide

    34/76

    callback.

    3 fs.ftruncateSyncfd,len Synchronous ftruncate

    4 fs.truncatepath,len,callback Asynchronous truncate. No arguments other than apossible exception are given to the completioncallback.

    5 fs.truncateSyncpath,len Synchronous truncate

    6 fs.chownpath,uid,gid,callback Asynchronous chown. No arguments other than apossible exception are given to the completioncallback.

    7 fs.chownSyncpath,uid,gid Synchronous chown

    8 fs.fchownfd,uid,gid,callback Asynchronous fchown. No arguments other than apossible exception are given to the completioncallback.

    9 fs.fchownSyncfd,uid,gid Synchronous fchown

    10 fs.lchownpath,uid,gid,callback Asynchronous lchown. No arguments other than apossible exception are given to the completion

    callback.

    11 fs.lchownSyncpath,uid,gid Synchronous lchown

    12 fs.chmodpath,mode,callback Asynchronous chmod. No arguments other than apossible exception are given to the completioncallback.

    13 fs.chmodSyncpath,mode Synchronous chmod.

    14 fs.fchmodfd,mode,callback Asynchronous fchmod. No arguments other than apossible exception are given to the completioncallback.

    15 fs.fchmodSyncfd,mode Synchronous fchmod.

    16 fs.lchmodpath,mode,callback Asynchronous lchmod. No arguments other than apossible exception are given to the completioncallback.Only available on Mac OS X.

    17 fs.lchmodSyncpath,mode Synchronous lchmod.

    18 fs.statpath,callback Asynchronous stat. The callback gets twoarguments err,statswhere stats is a fs.Stats object.

    19 fs.lstatpath,callback Asynchronous lstat. The callback gets twoarguments err,statswhere stats is a fs.Stats object.

    lstat is identical to stat, except that if path is asymbolic link, then the link itself is stat-ed, not thefile that it refers to.

    20 fs.fstatfd,callback Asynchronous fstat. The callback gets twoarguments err,statswhere stats is a fs.Stats object.fstat is identical to stat, except that the file to bestat-ed is specified by the file descriptor fd.

    21 fs.statSyncpath Synchronous stat. Returns an instance of fs.Stats.

    22 fs.lstatSyncpath Synchronous lstat. Returns an instance of fs.Stats.

    23 fs.fstatSyncfd Synchronous fstat. Returns an instance of fs.Stats.

    24 fs.linksrcpath,dstpath,callback Asynchronous link. No arguments other than apossible exception are given to the completioncallback.

    25 fs.linkSyncsrcpath,dstpath Synchronous link.

  • 7/26/2019 Nodejs Quick Guide

    35/76

    26 fs.symlinksrcpath,dstpath[,type],callback

    Asynchronous symlink. No arguments other than apossible exception are given to the completioncallback. The type argument can be set to 'dir',

    'file', or 'junction' defaultisfile and is only availableon Windows ignoredonotherplatforms. Note thatWindows junction points require the destinationpath to be absolute. When using 'junction', thedestination argument will automatically benormalized to absolute path.

    27 fs.symlinkSyncsrcpath,dstpath[,type] Synchronous symlink.

    28 fs.readlinkpath,callback Asynchronous readlink. The callback gets twoarguments err,linkString.

    29 fs.realpathpath[, cache],callback Asynchronous realpath. The callback gets twoarguments err, resolvedPath. May use process.cwd toresolve relative paths. cache is an object literal ofmapped paths that can be used to force a specificpath resolution or avoid additional fs.stat calls forknown real paths.

    30 fs.realpathSyncpath[,cache] Synchronous realpath. Returns the resolved path.

    31 fs.unlinkpath,callback Asynchronous unlink. No arguments other than apossible exception are given to the completioncallback.

    32 fs.unlinkSyncpath Synchronous unlink.

    33 fs.rmdirpath,callback Asynchronous rmdir. No arguments other than apossible exception are given to the completioncallback.

    34 fs.rmdirSyncpath Synchronous rmdir.

    35 fs.mkdirpath[,mode],callback SAsynchronous mkdir2. No arguments other than a

    possible exception are given to the completioncallback. mode defaults to 0777.

    36 fs.mkdirSyncpath[,mode] Synchronous mkdir.

    37 fs.readdirpath,callback Asynchronous readdir3. Reads the contents of adirectory. The callback gets two arguments err,fileswhere files is an array of the names of the files inthe directory excluding '.' and '..'.

    38 fs.readdirSyncpath Synchronous readdir. Returns an array offilenames excluding '.' and '..'.

    39 fs.closefd,callback Asynchronous close. No arguments other than a

    possible exception are given to the completioncallback.

    40 fs.closeSyncfd Synchronous close.

    41 fs.openpath,flags[,mode], callback Asynchronous file open.

    42 fs.openSyncpath,flags[,mode] Synchronous version of fs.open.

    43 fs.utimespath,atime,mtime,callback

    44 fs.utimesSyncpath,atime,mtime Change file timestamps of the file referenced bythe supplied path.

    45 fs.futimesfd,atime,mtime,callback

    46 fs.futimesSyncfd,atime,mtime Change the file timestamps of a file referenced bythe supplied file descriptor.

    47 fs.fsyncfd,callback Asynchronous fsync2. No arguments other than a

  • 7/26/2019 Nodejs Quick Guide

    36/76

    possible exception are given to the completioncallback.

    48 fs.fsyncSyncfd Synchronous fsync2.

    49 fs.writefd,buffer,offset,length[,position],callback

    Write buffer to the file specified by fd.

    50 fs.writefd,data[,position[,encoding]], callback

    Write data to the file specified by fd. If data is not aBuffer instance then the value will be coerced to a

    string.

    51 fs.writeSyncfd,buffer,offset,length[,position]

    Synchronous versions of fs.write. Returns thenumber of bytes written.

    52 fs.writeSyncfd,data[,position[,encoding]]

    Synchronous versions of fs.write. Returns thenumber of bytes written.

    53 fs.readfd,buffer,offset,length,position,callback

    Read data from the file specified by fd.

    54 fs.readSyncfd,buffer,offset,length,position

    Synchronous version of fs.read. Returns thenumber of bytesRead.

    55 fs.readFilefilename[,options],callback Asynchronously reads the entire contents of a file.

    56 fs.readFileSyncfilename[,options] Synchronous version of fs.readFile. Returns thecontents of the filename.

    57 fs.writeFilefilename,data[,options],callback

    Asynchronously writes data to a file, replacing thefile if it already exists. data can be a string or abuffer.

    58 fs.writeFileSyncfilename,data[,options]

    The synchronous version of fs.writeFile.

    59 fs.appendFilefilename,data[,options],callback

    Asynchronously append data to a file, creating thefile if it not yet exists. data can be a string or abuffer.

    60 fs.appendFileSyncfilename,data[,options]

    The synchronous version of fs.appendFile.

    61 fs.watchFilefilename[,options], listener Watch for changes on filename. The callbacklistener will be called each time the file isaccessed.

    62 fs.unwatchFilefilename[, listener] Stop watching for changes on filename. If listeneris specified, only that particular listener isremoved. Otherwise, all listeners are removed andyou have effectively stopped watching filename.

    63 fs.watchfilename[,options][, listener] Watch for changes on filename, where filename iseither a file or a directory. The returned object is afs.FSWatcher.

    64 fs.existspath,callback Test whether or not the given path exists bychecking with the file system. Then call thecallback argument with either true or false.

    65 fs.existsSyncpath Synchronous version of fs.exists.

    66 fs.accesspath[,mode],callback Tests a user's permissions for the file specified bypath. mode is an optional integer that specifies theaccessibility checks to be performed.

    67 fs.accessSyncpath[,mode] Synchronous version of fs.access. This throws ifany accessibility checks fail, and does nothingotherwise.

    68 fs.createReadStreampath[,options] Returns a new ReadStream object.

  • 7/26/2019 Nodejs Quick Guide

    37/76

    69 fs.createWriteStreampath[,options] Returns a new WriteStream object.

    70 fs.symlinksrcpath,dstpath[,type],callback

    Asynchronous symlink. No arguments other than apossible exception are given to the completioncallback. The type argument can be set to 'dir',

    'file', or 'junction' defaultisfile and is only availableon Windows ignoredonotherplatforms. Note thatWindows junction points require the destinationpath to be absolute. When using 'junction', thedestination argument will automatically be

    normalized to absolute path.

    Flags

    flags for read/write operations are:

    r- Open file for reading. An exception occurs if the file does not exist.

    r+- Open file for reading and writing. An exception occurs if the file does not exist.

    rs- Open file for reading in synchronous mode. Instructs the operating system to bypass thelocal file system cache. This is primarily useful for opening files on NFS mounts as it allows

    you to skip the potentially stale local cache. It has a very real impact on I/O performance sodon't use this flag unless you need it. Note that this doesn't turn fs.open into a synchronousblocking call. If that's what you want then you should be using fs.openSync

    rs+- Open file for reading and writing, telling the OS to open it synchronously. See notes for'rs' about using this with caution.

    w- Open file for writing. The file is created ifitdoesnotexistor truncated ifitexists.

    wx- Like 'w' but fails if path exists.

    w+- Open file for reading and writing. The file is created ifitdoesnotexistor truncated ifitexists.

    wx+- Like 'w+' but fails if path exists.

    a- Open file for appending. The file is created if it does not exist.

    ax- Like 'a' but fails if path exists.

    a+- Open file for reading and appending. The file is created if it does not exist.

    ax+'- Like 'a+' but fails if path exists.

    Example

    Create a txt file named test.txt in C:\>Nodejs_WorkSpace

    TutorialsPoint.Com

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varfs =require("fs");varbuffer =newBuffer(1024);

    //Example: Opening FilefunctionopenFile(){ console.log("\nOpen file"); fs.open('test.txt','r+',function(err,fd){

    if(err)console.log(err.stack); console.log("File opened");

    });}

    //Example: Getting File InfofunctiongetStats(){ console.log("\nGetting File Info"); fs.stat('test.txt',function(err,stats){

  • 7/26/2019 Nodejs Quick Guide

    38/76

    if(err)console.log(err.stack); console.log(stats); console.log("isFile ? "+stats.isFile()); console.log("isDirectory ? "+stats.isDirectory());

    });}

    //Example: Writing FilefunctionwriteFile(){ console.log("\nWrite file"); fs.open('test1.txt','w+',function(err,fd){

    vardata ="TutorialsPoint.com - Simply Easy Learning!"; buffer.write(data);

    fs.write(fd,buffer,0,data.length,0,function(err,bytes){

    if(err)console.log(err.stack); console.log(bytes +" written!");

    });});

    }

    //Example: Read FilefunctionreadFile(){ console.log("\nRead file"); fs.open('test1.txt','r+',function(err,fd){

    if(err)console.log(err.stack); fs.read(fd,buffer,0,buffer.length,0,function(err,bytes){ if(err)console.log(err.stack); console.log(bytes +" read!"); if(bytes >0){ console.log(buffer.slice(0,bytes).toString()); } });

    });}

    functioncloseFile(){ console.log("\nClose file"); fs.open('test.txt','r+',function(err,fd){ if(err)console.log(err.stack);

    fs.close(fd,function(){ if(err)console.log(err.stack);

    console.log("File closed!"); }); });}

    functiondeleteFile(){ console.log("\nDelete file"); fs.open('test1.txt','r+',function(err,fd){ fs.unlink('test1.txt',function(err){ if(err)console.log(err.stack);

    console.log("File deleted!");});

    });}

    functiontruncateFile(){ console.log("\nTruncate file"); fs.open('test.txt','r+',function(err,fd){ fs.ftruncate(fd,function(err){ if(err)console.log(err.stack);

    console.log("File truncated!");});

    });}

    functioncreateDirectory(){

    console.log("\nCreate Directory");fs.mkdir('test',function(err){ if(!err){ console.log("Directory created!"); } if(err &&err.code ==='EEXIST'){ console.log("Directory exists!");

  • 7/26/2019 Nodejs Quick Guide

    39/76

    }elseif(err){console.log(err.stack);

    }});}

    functionremoveDirectory(){

    console.log("\nRemove Directory");fs.rmdir('test',function(err){ if(!err){ console.log("Directory removed!");

    } if(err){

    console.log("Directory do not exist!");}

    });}

    functionwatchFile(){ fs.watch('test.txt',function(event,filename){ console.log('event is: '+event);

    });}

    //Opening file

    openFile();

    //Writing File

    writeFile();

    //Reading FilereadFile();

    //Closing FilescloseFile();

    //Getting file informationgetStats();

    //Deleting FilesdeleteFile();//Truncating FilestruncateFile();//Creating DirectoriescreateDirectory();

    //Removing Directories

    removeDirectory();//Watching File ChangeswatchFile();

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output.

    Open file

    Write file

    Read file

    Close file

    Getting File Info

    Delete file

  • 7/26/2019 Nodejs Quick Guide

    40/76

    Truncate file

    Create Directory

    Remove DirectoryFile opened{ dev: 0,

    mode: 33206, nlink: 1, uid: 0, gid: 0,

    rdev: 0, ino: 0, size: 0, atime: Fri Jan 01 2010 00:02:15 GMT+0530 (India Standard Time), mtime: Sun Feb 15 2015 13:33:09 GMT+0530 (India Standard Time), ctime: Fri Jan 01 2010 00:02:15 GMT+0530 (India Standard Time) }isFile ? true

    isDirectory ? falseDirectory created!Directory removed!event is: renameevent is: rename42 written!42 read!

    TutorialsPoint.com - Simply Easy Learning!File closed!File deleted!

    File truncated!event is: change

    NODE.JS - UTILITY MODULESNODE.JS - UTILITY MODULES

    In this article, we'll discuss some of the utility modules provided by Node.js library which are verycommon and are frequently used across the applications.

    Sr.No. Module Name & Description

    1 ConsoleUsed to print information on stdout and stderr.

    2 ProcessUsed to get information on current process. Provides multiple events related toprocess activities.

    3 OS ModuleProvides basic operating-system related utility functions.

    4 Path ModuleProvides utilities for handling and transforming file paths.

    5 Net ModuleProvides both servers and clients as streams. Acts as a network wrapper.

    6 DNS ModuleProvides functions to do actual DNS lookup as well as to use underlying operatingsystem name resolution functionalities.

    7 Domain ModuleProvides way to handle multiple different I/O operations as a single group.

    NODE.JS - CONSOLENODE.JS - CONSOLE

    consoleis a global object and is used to print to stdout and stderr. It is used in synchronous waywhen destination is file or a terminal and asynchronous way when destination is a pipe.

    Methods

  • 7/26/2019 Nodejs Quick Guide

    41/76

    Sr.No.

    method Description

    1 console.log[data][, . . . ]

    Prints to stdout with newline. This function can take multiplearguments in a printf-like way.

    2 console.info[data][, . . . ]

    Prints to stdout with newline. This function can take multiplearguments in a printf-like way.

    3 console.error

    [data][, . . . ]

    Prints to stderr with newline. This function can take multiple

    arguments in a printf-like way.

    4 console.warn[data][, . . . ]

    Prints to stderr with newline. This function can take multiplearguments in a printf-like way

    5 console.dirobj[,options]

    Uses util.inspect on obj and prints resulting string to stdout.

    6 console.timelabel Mark a time.

    7 console.timeEndlabel

    Finish timer, record output.

    8 console.trace

    message[, . . . ]

    Print to stderr 'Trace :', followed by the formatted message and

    stack trace to the current position.

    9 console.assertvalue[, message][, . . . ]

    Similar to assert.ok, but the error message is formatted asutil.formatmessage. . . .

    Example

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varcounter =10;

    console.log("Counter: %d",counter);

    console.time("Getting data");//make a database call to retrive the data//getDataFromDataBase();console.timeEnd('Getting data');

    console.info("Program Ended!")

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output.

    Counter: 10Getting data: 0msProgram Ended!

    NODE.JS - PROCESSNODE.JS - PROCESS

    processis a global object and is used to represent Node process.

    Exit Codes

    Node normally exit with a 0 status code when no more async operations are pending. There areother exit codes which are described below:

    Code Name Description

  • 7/26/2019 Nodejs Quick Guide

    42/76

    1 UncaughtFatalException

    There was an uncaught exception, and it was not handled by a domain oran uncaughtException event handler.

    2 Unused reserved by Bash for builtin misuse

    3 InternalJavaScriptParseError

    The JavaScript source code internal in Node's bootstrapping processcaused a parse error. This is extremely rare, and generally can onlyhappen during development of Node itself.

    4 InternalJavaScriptEvaluationFailure

    The JavaScript source code internal in Node's bootstrapping processfailed to return a function value when evaluated. This is extremely rare,and generally can only happen during development of Node itself.

    5 FatalError

    There was a fatal unrecoverable error in V8. Typically a message will beprinted to stderr with the prefix FATAL ERROR.

    6 Non-functionInternalException

    Handler

    There was an uncaught exception, but the internal fatal exceptionhandler function was somehow set to a non-function, and could not becalled.

    7 InternalExceptionHandlerRun-TimeFailure

    here was an uncaught exception, and the internal fatal exception handlerfunction itself threw an error while attempting to handle it.

    8 Unused

    9 InvalidArgument

    Either an unknown option was specified, or an option requiring a valuewas provided without a value.

    10 Internal

    JavaScriptRun-TimeFailure

    The JavaScript source code internal in Node's bootstrapping process

    threw an error when the bootstrapping function was called. This isextremely rare, and generally can only happen during development ofNode itself.

    12 InvalidDebugArgument

    The --debug and/or --debug-brk options were set, but an invalid portnumber was chosen.

    >128 SignalExits

    If Node receives a fatal signal such as SIGKILL or SIGHUP, then its exitcode will be 128 plus the value of the signal code. This is a standard Unixpractice, since exit codes are defined to be 7-bit integers, and signal exitsset the high-order bit, and then contain the value of the signal code.

    Events

    Process is an eventEmitter and it emits the following events.

    Sr.No. Event Description

    1 exit Emitted when the process is about to exit. There is no way toprevent the exiting of the event loop at this point, and once allexit listeners have finished running the process will exit.

    2 beforeExit This event is emitted when node empties it's event loop and

    has nothing else to schedule. Normally, node exits when thereis no work scheduled, but a listener for 'beforeExit' can makeasynchronous calls, and cause node to continue.

    3 uncaughtException Emitted when an exception bubbles all the way back to theevent loop. If a listener is added for this exception, the defaultaction whichistoprintastacktraceandexitwill not occur.

  • 7/26/2019 Nodejs Quick Guide

    43/76

    4 Signal Events Emitted when the processes receives a signal such as SIGINT,SIGHUP, etc.

    Properties

    Process provides many useful properties to get better control over system interactions.

    Sr.No. Property Description

    1 stdout A Writable Stream to stdout.

    2 stderr A Writable Stream to stderr.

    3 stdin A Writable Stream to stdin.

    4 argv An array containing the command line arguments. The first elementwill be 'node', the second element will be the name of the JavaScriptfile. The next elements will be any additional command linearguments.

    5 execPath This is the absolute pathname of the executable that started theprocess.

    6 execArgv This is the set of node-specific command line options from theexecutable that started the process.

    7 env An object containing the user environment.

    8 exitCode A number which will be the process exit code, when the process eitherexits gracefully, or is exited via process.exit without specifying a code.

    9 version A compiled-in property that exposes NODE_VERSION.

    10 versions A property exposing version strings of node and its dependencies.

    11 config An Object containing the JavaScript representation of the configureoptions that were used to compile the current node executable. This isthe same as the "config.gypi" file that was produced when running the./configure script.

    12 pid The PID of the process.

    13 title Getter/setter to set what is displayed in 'ps'.

    14 arch What processor architecture you're running on: 'arm', 'ia32', or 'x64'.

    15 platform What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or'win32'

    16 mainModule Alternate way to retrieve require.main. The difference is that if themain module changes at runtime, require.main might still refer to theoriginal main module in modules that were required before thechange occurred. Generally it's safe to assume that the two refer tothe same module.

    Methods

    Process provides many useful methods to get better control over system interactions.

    Sr.No. Method Description

    1 abort This causes node to emit an abort. This will cause node to exit andgenerate a core file.

    2 chdirdirectory Changes the current working directory of the process or throws an

  • 7/26/2019 Nodejs Quick Guide

    44/76

    exception if that fails.

    3 cwd Returns the current working directory of the process.

    4 exit[code] Ends the process with the specified code. If omitted, exit uses the'success' code 0.

    5 getgid Gets the group identity of the process. This is the numerical groupid, not the group name.This function is only available on POSIXplatforms i.e.notWindows,Android.

    6 setgidid Sets the group identity of the process. Seesetgid(2.) This accepts eithera numerical ID or a groupname string. If a groupname is specified,this method blocks while resolving it to a numerical ID.This functionis only available on POSIX platforms i.e.notWindows,Android.

    7 getuid Gets the user identity of the process. This is the numerical id, not theusername.This function is only available on POSIX platformsi.e.notWindows,Android.

    8 setuidid Sets the user identity of the process. Seesetgid(2.) This accepts either anumerical ID or a username string. If a username is specified, thismethod blocks while resolving it to a numerical ID.This function isonly available on POSIX platforms i.e.notWindows,Android.

    9 getgroups Returns an array with the supplementary group IDs. POSIX leaves itunspecified if the effective group ID is included but node.js ensuresit always is.This function is only available on POSIX platformsi.e.notWindows,Android.

    10 setgroupsgroups

    Sets the supplementary group IDs. This is a privileged operation,meaning you need to be root or have the CAP_SETGIDcapability.This function is only available on POSIX platformsi.e.notWindows,Android.

    11 initgroupsuser,extragroup

    Reads /etc/group and initializes the group access list, using allgroups of which the user is a member. This is a privileged operation,meaning you need to be root or have the CAP_SETGIDcapability.This function is only available on POSIX platformsi.e.notWindows,Android.

    12 killpid[,signal] Send a signal to a process. pid is the process id and signal is thestring describing the signal to send. Signal names are strings like'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.

    13 memoryUsage Returns an object describing the memory usage of the Nodeprocess measured in bytes.

    14 nextTickcallback

    Once the current event loop turn runs to completion, call thecallback function.

    15 umask[mask] Sets or reads the process's file mode creation mask. Child processesinherit the mask from the parent process. Returns the old mask ifmask argument is given, otherwise returns the current mask.

    16 uptime Number of seconds Node has been running.

    17 hrtime Returns the current high-resolution real time in a [seconds,nanoseconds] tuple Array. It is relative to an arbitrary time in thepast. It is not related to the time of day and therefore not subject toclock drift. The primary use is for measuring performance betweenintervals.

    ExampleCreate a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varutil =require('util');

  • 7/26/2019 Nodejs Quick Guide

    45/76

    //printing to consoleprocess.stdout.write("Hello World!"+"\n");

    //reading passed parameterprocess.argv.forEach(function(val,index,array){ console.log(index +': '+val);

    });

    //executable pathconsole.log(process.execPath);

    //print the current directoryconsole.log('Current directory: '+process.cwd());//print the process versionconsole.log('Current version: '+process.version);

    //print the memory usageconsole.log(util.inspect(process.memoryUsage()));

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output.

    Hello World!

    0: node1: C:\Nodejs_WorkSpace\test.js2: one3: 24: threeC:\Program Files\nodejs\node.exeCurrent directory: C:\Nodejs_WorkSpaceCurrent version: v0.10.36{ rss: 9314304, heapTotal: 3047296, heapUsed: 1460196 }

    NODE.JS - OS MODULENODE.JS - OS MODULEosmodule is used for few basic operating-system related utility functions. os module can beimported using following syntax.

    varos =require("os")

    Methods

    Sr.No.

    method Description

    1 os.tmpdir Returns the operating system's default directory for temp files.

    2 os.endianness Returns the endianness of the CPU. Possible values are "BE" or "LE".

    3 os.hostname Returns the hostname of the operating system.

    4 os.type Returns the operating system name.

    5 os.platform Returns the operating system platform.

    6 os.arch Returns the operating system CPU architecture. Possible values are"x64", "arm" and "ia32".

    7 os.release Returns the operating system release.

    8 os.uptime Returns the system uptime in seconds.

    9 os.loadavg Returns an array containing the 1, 5, and 15 minute load averages.

    10 os.totalmem Returns the total amount of system memory in bytes.

  • 7/26/2019 Nodejs Quick Guide

    46/76

    11 os.freemem Returns the amount of free system memory in bytes.

    12 os.cpus Returns an array of objects containing information about each CPU/coreinstalled: model, speed inMHz, and timesanobjectcontainingthenumberofmillisecondstheCPU/corespentin:user,nice,sys,idle,andirq

    .

    13 os.networkInterfaces Get a list of network interfaces.

    Properties

    Sr.No.

    property Description

    1 os.EOL A constant defining the appropriate End-of-line marker for the operatingsystem.

    Example

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varos =require("os");

    //endiannessconsole.log('endianness : '+os.endianness());

    //typeconsole.log('type : '+os.type());

    //platformconsole.log('platform : '+os.platform());

    //totalmemconsole.log('total memory : '+os.totalmem()+" bytes.");

    //freememconsole.log('free memory : '+os.freemem()+" bytes.");

    Now run the test.js to see the result:

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output.

    endianness : LEtype : Windows_NTplatform : win32total memory : 1072152576 bytes.free memory : 461508608 bytes.

    NODE.JS - PATH MODULENODE.JS - PATH MODULE

    pathmodule is used for handling and transforming file paths. path module can be imported usingfollowing syntax.

    varpath =require("path")

    Properties

    Process provides many useful properties to get better control over system interactions.

    Sr.No. Property Description

  • 7/26/2019 Nodejs Quick Guide

    47/76

    1 path.sep The platform-specific file separator. '\\' or '/'.

    2 path.delimiter The platform-specific path delimiter, ; or ':'.

    3 path.posix Provide access to aforementioned path methods but always interactin a posix compatible way.

    4 path.win32 Provide access to aforementioned path methods but always interactin a win32 compatible way.

    Methods

    Sr.No.

    method Description

    1 path.normalizep Normalize a string path, taking care of '..' and '.' parts.

    2 path.join[path1][,path2][, ...]

    Join all arguments together and normalize the resulting path.

    3 path.resolve[from ...],to Resolves to to an absolute path.

    4 path.isAbsolutepath Determines whether path is an absolute path. An absolutepath will always resolve to the same location, regardless ofthe working directory.

    5 path.relativefrom, to Solve the relative path from from to to.

    6 path.dirnamep Return the directory name of a path. Similar to the Unixdirname command.

    7 path.basenamep[, ext] Return the last portion of a path. Similar to the Unixbasename command.

    8 path.extnamep Return the extension of the path, from the last '.' to end ofstring in the last portion of the path. If there is no '.' in the lastportion of the path or the first character of it is '.', then itreturns an empty string.

    9 path.parsepathString Returns an object from a path string.

    10 path.formatpathObject Returns a path string from an object, the opposite ofpath.parse above.

    Example

    Create a js file named test.js in C:\>Nodejs_WorkSpace.

    File: test.js

    varpath =require("path");

    //normalizationconsole.log('normalization : '+path.normalize('/test/test1//2slashes/1slash/tab/..'));

    //joinconsole.log('joint path : '+path.join('/test','test1','2slashes/1slash','tab','..'));

    //resolve

    console.log('resolve : '+path.resolve('test.js'));

    //extNameconsole.log('ext name : '+path.extname('test.js'));

    Now run the test.js to see the result:

  • 7/26/2019 Nodejs Quick Guide

    48/76

    C:\Nodejs_WorkSpace>node test.js

    Verify the Output.

    normalization : \test\test1\2slashes\1slashjoint path : \test\test1\2slashes\1slashresolve : C:\Nodejs_WorkSpace\test.jsext name : .js

    NODE.JS - NET MODULENODE.JS - NET MODULE

    netmodule is used to create both servers and clients. It provides an aynchronous networkwrapper. net module can be imported using following syntax.

    varnet =require("net")

    Methods

    Sr.No.

    method Description

    1 net.createServer[options][,connectionListener]

    Creates a new TCP server. The connectionListenerargument is automatically set as a listener for the'connection' event.

    2 net.connectoptions[,connectionListener]

    A factory method, which returns a new 'net.Socket'and connects to the supplied address and port.

    3 net.createConnectionoptions[,connectionListener]

    A factory method, which returns a new 'net.Socket'and connects to the supplied address and port.

    4 net.connectport[, host][,connectListener]

    Creates a TCP connection to port on host. If host isomitted, 'localhost' will be assumed. TheconnectListener parameter will be added as anlistener for the 'connect' event. Is a factory methodwhich returns a new 'net.Socket'.

    5 net.createConnectionport[,host][, connectListener]

    Creates a TCP connection to port on host. If host isomitted, 'localhost' will be assumed. TheconnectListener parameter will be added as anlistener for the 'connect' event. Is a factory methodwhich returns a new 'net.Socket'.

    6 net.connectpath[,connectListener]

    Creates unix socket connection to path. TheconnectListener parameter will be added as anlistener for the 'connect' event. A factory methodwhich returns a new 'net.Socket'.

    7 net.createConnectionpath[,connectListener]

    Creates unix socket connection to path. TheconnectListener parameter will be added as anlistener for the 'connect' event. A factory methodwhich returns a new 'net.Socket'.

    8 net.isIPinput Tests if input is an IP address. Returns 0 for invalidstrings, returns 4 for IP version 4 addresses, andreturns 6 for IP version 6 addresses.

    9 net.isIPv4input Returns true if input is a version 4 IP address,otherwise returns false.

    10 net.isIPv6input Returns true if input is a version 6 IP address,otherwise returns false.

    Class:net.Server

    This class is used to create a TCP or local server.

  • 7/26/2019 Nodejs Quick Guide

    49/76

    Methods

    Sr.No.

    method Description

    1 server.listenport[, host][,backlog][, callback]

    Begin accepting connections on the specified portand host. If the host is omitted, the server will acceptconnections directed to any IPv4 addressINADDR_ANY. A port value of zero will assign a

    random port.

    2 server.listenpath[, callback] Start a local socket server listening for connectionson the given path.

    3 server.listenhandle[, callback] The handle object can be set to either a server orsocket anything with an underlying _handle member,or a {fd: } object. This will cause the server toaccept connections on the specified handle, but it ispresumed that the file descriptor or handle hasalready been bound to a port or domain socket.Listening on a file descriptor is not supported onWindows.

    4 server.listenoptions[,callback]

    The port, host, and backlog properties of options, aswell as the optional callback function, behave as theydo on a call to server.listenport, [host], [backlog],[callback]. Alternatively, the path option can be usedto specify a UNIX socket.

    5 server.close[callback] finally closed when all connections are ended andthe server emits a 'close' event.

    6 server.address Returns the bound address, the address family nameand port of the server as reported by the operatingsystem.

    7 server.unref Cal