Quick Reference Study Notes for NodeJS 8 (Advanced)

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.

Console
Error events emitted when using console methods are now suppressed

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

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

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.

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:

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.

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.

Console
Error events emitted when using console methods are now suppressed

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

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

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.

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:

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.

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

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.

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

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

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:

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.

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!!!!!

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.

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

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

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:

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.

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!!!!!