Nods.js Basics

CommonJS Module format

Each file in a node is its own module.

The require function is used to import a module. (eg. require(‘./abc’))


Installing external yargs node module to take command line args

npm install yargs –save  (to save dependencies in package.json file)


Postman chrome extension for viewing the http request and response messages

nodejs ht


FileSystem Module:

Non Blocking call to read a file

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);

Blocking call to read a file

var fs = require("fs"); 
var data = fs.readFileSync('input.txt');


Events Module:

// Import events module
var events = require('events');

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// Bind event and even handler as follows
eventEmitter.on('eventName', eventHandler);

// Fire an event 

Streams are objects that let you read data from a source or write data to a destination in continous fashion. In Node.js, there are four types of streams.
Readable, Writable, Duplex, Transform.

Each type of Stream is an EventEmitter instance and throws several events at different instance of times.

Events thrown by the streams.
data, end, error, finish.

Read Stream Example

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

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Set the encoding to be utf8. 

// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
   data += chunk;
readerStream.on('error', function(err){
console.log("Program Ended");

Write stream example

var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8

// Mark the end of file

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed.");
writerStream.on('error', function(err){
console.log("Program Ended");

Piping Streams
Piping is a mechanism where we provide output of one stream as the input 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 on piping operations.

var fs = require("fs");

// Create a readable stream
var readerStream = fs.createReadStream('input.txt');

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Pipe the read and write operations
// read input.txt and write data to output.txt

console.log("Program Ended");

Chaining StreamsChanining is a mechanism to connect output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.

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

// Compress the file input.txt to input.txt.gz
console.log("File Compressed.");

Buffer Module:

Buffer class provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.

Buffer class is a global class and can be accessed in application without importing buffer module.

Node Buffer can be constructed in a variety of ways.

1) var buf = new Buffer(10);
2) var buf = new Buffer([10, 20, 30, 40, 50]);
3) var buf = new Buffer("Simply Easy Learning", "utf-8");

To write into a Node Buffer:
  write returns the number of bytes written

buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+  len);

To convert a Node Buffer into JSON object:
Returns a JSON-representation of the Buffer instance.

Concatenation:  Buffer.concat([buffer1,buffer2]);

Compare Buffers :;

Copy Buffers: buffer1.copy(buffer2);

Buffer length: buffer.length;

Slice Buffer: buffer.slice(0,9);


Global Objects: Node.js global objects are global in nature we do not need to include these objects in our application, rather we can use them directly.
These objects are modules, functions, strings and object itself.

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file
console.log( __filename );
The __dirname represents the name of the directory that the currently executing script resides in.
console.log( __dirname );
Console:console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning and error messages.

It is used in synchronous way when destination is file or a terminal and asynchronous way when destination is a pipe.

eg."Program Started");
var counter = 10;
console.log("Counter: %d", counter);

console.time("Getting data");


Process: The process object is a global object and can be accessed from anywhere. There are number of useful methods available through a process object.

The process object is an instance of EventEmitter and emits following events:

exit, beforeExit, uncaughtException, Signal Events

Process object also provides many useful properties and method reference.


Global Functions:

setTimeout(cb, ms)
The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds.
This function returns an opaque value that represents the timer which can be used to clear the timer.
clearTimeout(t):Global function is used to stop a timer that was previously created with setTimeout().
setInterval(cb, ms)The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds.
clearInterval(t): Is used to clear an interval.


Web Module

var http = require('http');
// creating server

// creating client
var options = {
   host: 'localhost',
   port: '8081',
   path: '/index.htm'  

var req = http.request(options, callback);

Callback functions: In Node Application, any async function accepts a callback as a last parameter and the callback function accepts error as a first parameter.

Leave a Reply

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

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s