Quick Reference Study Notes for NodeJS 8 (Advanced)


NodeJs

Basic Concept

Node.js is an open source server environment. It allows you to run javascript on the server.Node is single-threaded and uses a concurrency model based on an event loop. It is non-blocking, so it doesn't make the program wait, but instead,  it registers a callback and lets the program continue. This means it can handle concurrent operations without multiple threads of execution.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows you to perform other tasks while waiting to be notified when the response is available.

New Features

  1. Buffer 
    Buffer methods now accept Uint8Array as input

  2. Child Process
    Argument and kill signal validations have been improved
    Child Process methods accept Uint8Array as input

  3. Console
    Error events emitted when using console methods are now suppressed

  4. File System
    The utility class fs.SyncWriteStream has been deprecated
    The deprecated fs.read() string interface has been removed

  5. HTTP
    Outgoing Cookie headers are concatenated into a single string
    The httpResponse.writeHeader() method has been deprecated

  6. Stream
    Stream now supports destroy() and _destroy() APIs


Javascript concept

Non Blocking I/O

When the request comes to the server, it triggers off of passing request & doesn’t wait for the response. During this time it has some amount of free time which can be managed for getting more request from our clients.

Non-Blocking refers to code that doesn’t block execution. One advantage of non-blocking, asynchronous operations is that you can maximize the usage of a single CPU as well as memory.

Blocking node js code:

const fs = require('fs');
// account.txt : Hello Java.
let contents = fs.readFileSync('account.txt', 'utf8');
console.log(contents);
console.log('Hello Ruby.');
// acc.txt: Hello C++
let contents = fs.readFileSync('acc.txt', 'utf8');
console.log(contents);
console.log('Hello Node');

 

output: Hello Java. Hello Ruby. Hello C++. Hello Node
 

Non blocking nodejs code:

const fs = require ('fs');
// account.txt : Hello Java.
fs.readFile('account.txt', 'utf8', function(error, contents){
console.log(contents);
})
console.log(‘Hello Ruby.’);
// acc.txt: Hello C++
fs.readFile('acc.txt','utf8', function(error, contents){
console.log(contents);
})
console.log(‘Hello Node.’);

Output : Hello Ruby. Hello Node. Hello Java. Hello C++


Prototypes

A Prototype is the concept of javascript. You first create an object in JavaScript and then augment your own object or create new objects from it. This is called prototypal inheritance, meaning objects are implemented through the prototype, not through classes. sample code:

if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
 

var otherPerson = Object.create(person);

Here we are adding a create method to the object function. The create method creates a new object that uses another object as its prototype by passing the other object as an argument to the create method. When we make changes to the new object, its prototype remains unaffected. But when we make changes to the prototype object, the changes becomes visible in all the objects that are based on that prototype.

Node Modules

Modules are simple JavaScript files that contain code for a specific purpose. The module pattern is used to make your code easy to navigate and work with. To use the properties of a module, you have to require it in a JavaScript file much like the same as you import packages in a Java class. There are two types of modules in Node.js:

 

Core Modules – Core Modules are the ones that come pre-compiled with the Node.js library. The purpose of core modules is to provide developers with often occurring and repeating code sections that, if they were not available, developer have to write the same code again and again. Some common core modules are HTTP, URL, EVENTS, FILE SYSTEM, etc.

User Defined Modules – User defined modules are the ones which a developer makes for a specific purpose in his/her application. These are required when the core modules are not capable of fulfilling the desired functionality.

Modules are extracted via the require function. If it’s a core module, the argument is simply the name of that module. If it's a user defined module, then the argument is the path of that module in the file system.

For example,
// core module like this
var http = require('http);
//  user defined module like this
var something = require('./folder1/folder2/folder3/something.js');

Callbacks Methods

Callbacks are the most widely used for functional programming that can be passed as arguments to other functions and it can be executed or returned from that function to be executed later. When we pass a callback function as an argument to another function, we only pass the function definition, which means we never know when that callback function will be executed. The timing of the execution solely depends on the mechanism of the calling function. It is “called back” at some later point of time, hence the name. For example.

setTimeout(function() {
console.log("world");
}, 2000)

console.log("hello");

NodeJs

 

Basic Concept

Node.js is an open source server environment. It allows you to run javascript on the server.Node is single-threaded and uses a concurrency model based on an event loop. It is non-blocking, so it doesn't make the program wait, but instead,  it registers a callback and lets the program continue. This means it can handle concurrent operations without multiple threads of execution.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows you to perform other tasks while waiting to be notified when the response is available.

 

New Features

  1. Buffer
    Buffer methods now accept Uint8Array as input

  2. Child Process
    Argument and kill signal validations have been improved
    Child Process methods accept Uint8Array as input

  3. Console
    Error events emitted when using console methods are now suppressed

  4. File System
    The utility class fs.SyncWriteStream has been deprecated
    The deprecated fs.read() string interface has been removed

  5. HTTP
    Outgoing Cookie headers are concatenated into a single string
    The httpResponse.writeHeader() method has been deprecated

  6. Stream
    Stream now supports destroy() and _destroy() APIs

 

Javascript concept

Non Blocking I/O

When the request comes to the server, it triggers off of passing request & doesn’t wait for the response. During this time it has some amount of free time which can be managed for getting more request from our clients.

Non-Blocking refers to code that doesn’t block execution. One advantage of non-blocking, asynchronous operations is that you can maximize the usage of a single CPU as well as memory.

Blocking node js code:

const fs = require('fs');
// account.txt : Hello Java.
let contents = fs.readFileSync('account.txt', 'utf8');
console.log(contents);
console.log('Hello Ruby.');
// acc.txt: Hello C++
let contents = fs.readFileSync('acc.txt', 'utf8');
console.log(contents);
console.log('Hello Node');

 

output: Hello Java. Hello Ruby. Hello C++. Hello Node
 

Non blocking nodejs code:

const fs = require ('fs');
// account.txt : Hello Java.
fs.readFile('account.txt', 'utf8', function(error, contents){
console.log(contents);
})
console.log(‘Hello Ruby.’);
// acc.txt: Hello C++
fs.readFile('acc.txt','utf8', function(error, contents){
console.log(contents);
})
console.log(‘Hello Node.’);
Output : Hello Ruby. Hello Node. Hello Java. Hello C++


Prototypes

A Prototype is the concept of javascript. You first create an object in JavaScript and then augment your own object or create new objects from it. This is called prototypal inheritance, meaning objects are implemented through the prototype, not through classes. sample code:

if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
 

var otherPerson = Object.create(person);

Here we are adding a create method to the object function. The create method creates a new object that uses another object as its prototype by passing the other object as an argument to the create method. When we make changes to the new object, its prototype remains unaffected. But when we make changes to the prototype object, the changes becomes visible in all the objects that are based on that prototype.

 

Node Modules

Modules are simple JavaScript files that contain code for a specific purpose. The module pattern is used to make your code easy to navigate and work with. To use the properties of a module, you have to require it in a JavaScript file much like the same as you import packages in a Java class. There are two types of modules in Node.js:

Core Modules – Core Modules are the ones that come pre-compiled with the Node.js library. The purpose of core modules is to provide developers with often occurring and repeating code sections that, if they were not available, developer have to write the same code again and again. Some common core modules are HTTP, URL, EVENTS, FILE SYSTEM, etc.

User Defined Modules – User defined modules are the ones which a developer makes for a specific purpose in his/her application. These are required when the core modules are not capable of fulfilling the desired functionality.

Modules are extracted via the require function. If it’s a core module, the argument is simply the name of that module. If it's a user defined module, then the argument is the path of that module in the file system.

For example,
// core module like this
var http = require('http);
//  user defined module like this
var something = require('./folder1/folder2/folder3/something.js');

 

Callbacks Methods

Callbacks are the most widely used for functional programming that can be passed as arguments to other functions and it can be executed or returned from that function to be executed later. When we pass a callback function as an argument to another function, we only pass the function definition, which means we never know when that callback function will be executed. The timing of the execution solely depends on the mechanism of the calling function. It is “called back” at some later point of time, hence the name. For example.

setTimeout(function() {
console.log("world");
}, 2000)

console.log("hello");

it's only the function definition, the function doesn't know when to execute. The execution time is determined by the calling setTimeout function via the second argument, which determines that it will be executed after 2 seconds. First, the second log statement logs the output to the console and then after two seconds, the log statement in the callback function logs the output.

Output: hello
 World

Node Js Installation

  1. Open the official page for Node.js (https://nodejs.org/en/download) downloads and download Node.js for Windows by clicking the "Windows Installer" option.

  2. Run the downloaded Node.js .msi Installer - By accepting the license, selecting the destination, and authenticating for the installation. This requires Administrator privileges, and you may need to authenticate

  3. To ensure Node.js has been installed, run node -v in your terminal - you should get something like v6.9.5

  4. Update your version of npm with npm install npm --global. npm is a package manager for Node.js packages. This requires Administrator privileges, and you may need to authenticate
    Now your nodejs is installed.

 

Event Handling

Node.js has built-in module, called Events, where you can create-, fire-, and listen for- your events. To include built-in module use require() method. You can assign event handlers to your own events with the EventEmitter object. For example:

var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {
 console.log('I hear a scream!');
}
//Assign the eventhandler to an event:
eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');   output:  I hear a scream!

Node Js Express

Express is a minimal and flexible Node.js web application framework which provides set of features to develop web and mobile applications. It provides the facility to rapid development of Node based Web applications. It allows to set up middlewares to respond to HTTP Requests and dynamically render HTML Pages based on passing arguments to templates. You can install the Express framework globally using NPM so that it can be used to create a web application using node terminal.

$ npm install express --save

This command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express.

body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.

cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.

multer − This is a node.js middleware for handling multipart/form-data.

Following  is the command to install above three modules:

$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

Following is a very basic Express app which starts a server and listens on port 8081 for connection. This app responds with Hello World! for requests to the homepage.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World');
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  
  console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code in a file named server.js and run it using following commad:

$ node server.js

You will see the following output in command prompt:

Example app listening at http://127.0.0.1:8081

Open http://127.0.0.1:8081/ in any browser to see the following result.

                          

Express framework uses a callback function whose parameters are request and response.

app.get('/', function (req, res) {
  // --
})

Request Object − It represents the HTTP request and it has the properties for the requesting query string, parameters, body, HTTP headers etc.

Response Object − It represents the HTTP response that an app sends when it gets an HTTP request.

 

Error Handling

Node.js supports different methods for handling errors which occurs when an application is running. These errors handled according to the type of error and style of the API which is called.

  • Many asynchronous methods which accept a callback function will accept an Error object passed as the first argument to that function. For example:

const fs = require('fs');
 fs.readFile('a file that does not exist', (err, data) => {
   if (err) {
     console.error('There was an error reading the file!', err);
     return;
   }
   // Otherwise handle the data
 });

  • When an asynchronous method is called on an object which is an EventEmitter, errors can be routed to that object's 'error' event. For example:

const net = require('net');
const connection = net.connect('localhost');
// Adding an 'error' event handler to a stream:
connection.on('error', (err) => {
 // If the connection is reset by the server, or if it can't
 // connect at all, or on any sort of error encountered by
 // the connection, the error will be sent here.
 console.error(err);
});

 

Streams
Streams are the objects which read data from the source and write data to the destination. There are four types of streams in nodejs.

Readable: Streams used for read operation.

Writable: streams used for write operation.

Duplex: streams used for the both read and write operations.

Transform: It is type of duplex stream where the output is computed based on input.

 

Some of the commonly used events in stream 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 the data has been flushed to the underlying system.

Reading a Stream: Create a text file named input.txt having the following content −
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Create a file name read.js

var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.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");

 

run the main.js to see the result −
$ node read.js
Verify the Output.
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

 

Node Js Piping

In Node streams can be piped together using the pipe() method, which takes two arguments:

  • A Required writable stream.

  • An optional object used to pass in options.

Following is the example that how we can use pipe in node js:

Create a file input.txt which has the below data in  D drive:

Tutorial on Node.js
Introduction

Events
Generators
Data Connectivity
Using Jasmine

Now create a blank file output.txt in D drive

Now create the file main.js

var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('D://input.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('D://output.txt');
// Pipe the read and write operations
// read input.txt and write data to output.txt

readerStream.pipe(writerStream);
console.log("Program Ended");

Run command:   $ node main.js

Output: Program Ended

Now check your output.txt file which contains the data of the input.txt

File handling

Node Js ‘fs’ modules allow you to work with the file system. To include this use require() method. For example: var fs = require('fs'); Common use of file system module is for

Read files: fs.readFile() is used for reading a file.
Create files:  fs.writeFile() is used for writing a file.

Update files: fs.appendFile() is used for updating a file.
Delete files: fs.unlink() method deletes the specified file.
Rename files : fs.rename() method renames the specified file.

Output: hello
 World

 

Node Js Installation

  1. Open the official page for Node.js (https://nodejs.org/en/download) downloads and download Node.js for Windows by clicking the "Windows Installer" option.

  2. Run the downloaded Node.js .msi Installer - By accepting the license, selecting the destination, and authenticating for the installation. This requires Administrator privileges, and you may need to authenticate

  3. To ensure Node.js has been installed, run node -v in your terminal - you should get something like v6.9.5

  4. Update your version of npm with npm install npm --global. npm is a package manager for Node.js packages. This requires Administrator privileges, and you may need to authenticate
    Now your nodejs is installed.

 

Event Handling

Node.js has built-in module, called Events, where you can create-, fire-, and listen for- your events. To include built-in module use require() method. You can assign event handlers to your own events with the EventEmitter object. For example:

var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {
 console.log('I hear a scream!');
}
//Assign the eventhandler to an event:
eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');   output:  I hear a scream!

Node Js Express

Express is a minimal and flexible Node.js web application framework which provides set of features to develop web and mobile applications. It provides the facility to rapid development of Node based Web applications. It allows to set up middlewares to respond to HTTP Requests and dynamically render HTML Pages based on passing arguments to templates. You can install the Express framework globally using NPM so that it can be used to create a web application using node terminal.

$ npm install express --save

This command saves the installation locally in the node_modules directory and creates a directory express inside node_modules. You should install the following important modules along with express.

body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.

cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.

multer − This is a node.js middleware for handling multipart/form-data.

Following  is the command to install above three modules:

$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

Following is a very basic Express app which starts a server and listens on port 8081 for connection. This app responds with Hello World! for requests to the homepage.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World');
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  
  console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code in a file named server.js and run it using following commad:

$ node server.js

You will see the following output in command prompt:

Example app listening at http://127.0.0.1:8081

Open http://127.0.0.1:8081/ in any browser to see the following result.

                          

Express framework uses a callback function whose parameters are request and response.

app.get('/', function (req, res) {
  // --
})

Request Object − It represents the HTTP request and it has the properties for the requesting query string, parameters, body, HTTP headers etc.

Response Object − It represents the HTTP response that an app sends when it gets an HTTP request.

 

Error Handling

Node.js supports different methods for handling errors which occurs when an application is running. These errors handled according to the type of error and style of the API which is called.

  • Many asynchronous methods which accept a callback function will accept an Error object passed as the first argument to that function. For example:

const fs = require('fs');
 fs.readFile('a file that does not exist', (err, data) => {
   if (err) {
     console.error('There was an error reading the file!', err);
     return;
   }
   // Otherwise handle the data
 });

  • When an asynchronous method is called on an object which is an EventEmitter, errors can be routed to that object's 'error' event. For example:

const net = require('net');
const connection = net.connect('localhost');
// Adding an 'error' event handler to a stream:
connection.on('error', (err) => {
 // If the connection is reset by the server, or if it can't
 // connect at all, or on any sort of error encountered by
 // the connection, the error will be sent here.
 console.error(err);
});

 

Streams
Streams are the objects which read data from the source and write data to the destination. There are four types of streams in nodejs.

Readable: Streams used for read operation.

Writable: streams used for write operation.

Duplex: streams used for the both read and write operations.

Transform: It is type of duplex stream where the output is computed based on input.

 

Some of the commonly used events in stream 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 the data has been flushed to the underlying system.

Reading a Stream: Create a text file named input.txt having the following content −
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Create a file name read.js

var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.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");

 

run the main.js to see the result −
$ node read.js
Verify the Output.
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

 

Node Js Piping

In Node streams can be piped together using the pipe() method, which takes two arguments:

  • A Required writable stream.

  • An optional object used to pass in options.

Following is the example that how we can use pipe in node js:

Create a file input.txt which has the below data in  D drive:

Tutorial on Node.js
Introduction

Events
Generators
Data Connectivity
Using Jasmine

Now create a blank file output.txt in D drive

Now create the file main.js

var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('D://input.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('D://output.txt');
// Pipe the read and write operations
// read input.txt and write data to output.txt

readerStream.pipe(writerStream);
console.log("Program Ended");

Run command:   $ node main.js

Output: Program Ended

Now check your output.txt file which contains the data of the input.txt

File handling

Node Js ‘fs’ modules allow you to work with the file system. To include this use require() method. For example: var fs = require('fs'); Common use of file system module is for

Read files: fs.readFile() is used for reading a file.
Create files:  fs.writeFile() is used for writing a file.

Update files: fs.appendFile() is used for updating a file.
Delete files: fs.unlink() method deletes the specified file.
Rename files : fs.rename() method renames the specified file.

NOTE : "This study material is collected from multiple sources to make a quick refresh course available to students."

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree