NodeJs
NodeJs
INTRODUCTION
Q. What is Node.js?
Node.js is an open-source server side runtime environment built on
Chrome's V8 JavaScript engine. It provides an event driven, non-blocking
(asynchronous) I/O and cross-platform runtime environment for building
highly scalable server-side applications using JavaScript.
All the user requests to your web application will be handled by a single
thread and all the I/O work or long running job is performed
asynchronously for a particular request. So, this single thread doesn't
have to wait for the request to complete and is free to handle the next
request. When asynchronous I/O work completes then it processes the
request further and sends the response.
# 2. NODE.JS SETUP
mkdir myapp
cd myapp
Step 02: Initialize project and link it to npm
npm init
This creates a package.json file in your myapp folder. The file contains
references for all npm packages you have downloaded to your project.
The command will prompt you to enter a number of things. You can enter
your way through all of them EXCEPT this one:
app.js
Step 03: Install Express in the myapp directory
/**
* Express.js
*/
const express = require('express');
const app = express();
app.listen(3000, function () {
console.log('App listening on port 3000!');
});
Example:
/**
* URL Module in Node.js
*/
const url = require('url');
const adr = 'http://localhost:8080/default.htm?year=2022&month=september';
const q = url.parse(adr, true);
console.log(q.host); // localhost:8080
console.log(q.pathname); // "/default.htm"
console.log(q.search); // "?year=2022&month=september"
1. Primitives:
String
Number
BigInt
Boolean
Undefined
Null
Symbol
2. Objects:
Function
Array
Buffer
String functions:
Function Description
charAt() It is useful to find a specific character present in a string.
Concat() It is useful to concat more than one string.
indexOf(
It is useful to get the index of a specified character or a part of the string.
)
Match() It is useful to match multiple strings.
Split() It is useful to split the string and return an array of string.
Function Description
It is useful to join the array of strings and those are separated by comma (,)
Join()
operator.
Example:
/**
* String Data Type
*/
const str1 = "Hello";
const str2 = 'World';
Example:
/**
* Number Data Type
*/
// Example 01:
const num1 = 10;
const num2 = 20;
// Example 02:
console.log(parseInt("32")); // 32
console.log(parseFloat("8.24")); // 8.24
console.log(parseInt("234.12345")); // 234
console.log(parseFloat("10")); // 10
// Example 03:
console.log(isFinite(10/5)); // true
console.log(isFinite(10/0)); // false
// Example 04:
console.log(5 / 0); // Infinity
console.log(-5 / 0); // -Infinity
Example:
/**
* BigInt Data Type
*/
const maxSafeInteger = 99n; // This is a BigInt
const num2 = BigInt('99'); // This is equivalent
const num3 = BigInt(99); // Also works
Example:
/**
* Boolean Data Type
*/
// Example 01:
const isValid = true;
console.log(isValid); // true
// Example 02:
console.log(true && true); // true
console.log(true && false); // false
console.log(true || false); // true
console.log(false || false); // false
console.log(!true); // false
console.log(!false); // true
Example:
/**
* NULL and UNDEFINED Data Type
*/
let x;
console.log(x); // undefined
let y = null;
console.log(y); // null
Example:
/**
* Symbol Data Type
*/
const NAME = Symbol()
const person = {
[NAME]: 'Ritika Bhavsar'
}
Example:
/**
* Function in Node.js
*/
function Messsage(name) {
console.log("Hello "+name);
}
/**
* Buffer Data Type
*/
let b = new Buffer(10000);
let str = "----------";
b.write(str);
console.log( str.length ); // 10
console.log( b.length ); // 10000
Note: Buffer() is deprecated due to security and usability issues.
# 4. NODE.JS ARCHITECTURE
A new request coming in is one kind of event. The server starts processing
it and when there is a blocking IO operation, it does not wait until it
completes and instead registers a callback function. The server then
immediately starts to process another event ( maybe another request ).
When the IO operation is finished, that is another kind of event, and the
server will process it ( i.e. continue working on the request ) by executing
the callback as soon as it has time.
Syntax:
Core
Description
Module
assert provides a set of assertion functions useful for testing
console provides a simple debugging console
crypto provides cryptographic functionality
http module includes classes, methods and events to create Node.js http
http
server.
url url module includes methods for URL resolution and parsing.
querystring querystring module includes methods to deal with query string.
path path module includes methods to deal with file paths.
fs fs module includes classes, methods, and events to work with file I/O.
util util module includes utility functions useful for programmers.
1. Blocking I/O: Application will make a function call and pause its
execution at a point until the data is received. It is called as
"Synchronous".
3. Event Loop and Event Queue: Event Queue queues up the new
events that occurred along with its event-handler, pair.
1. global:
var myvar;
2. process:
3. console:
function printHello() {
console.log( "Hello, World!");
}
console.log(__dirname);
6. __filename:
It specifies the filename of the code being executed. This is the resolved
absolute path of this code file. The value inside a module is the path to
that module file.
console.log(__filename);
The V8 engine uses both a compiler and an interpreter and follows just-
in-time (JIT) compilation to speed up the execution. JIT compiling works
by compiling small portions of code that are just about to be executed.
This prevents long compilation time and the code being compiles is only
that which is highly likely to run.
# 5. NODE.JS EVENTS
Q. What is EventEmitter in Node.js?
The EventEmitter is a class that facilitates communication/interaction
between objects in Node.js. The EventEmitter class can be used to create
and handle custom events.
/**
* Callbacks Events
*/
const events = require('events');
const eventEmitter = new events.EventEmitter();
function listenerOne() {
console.log('First Listener Executed');
}
function listenerTwo() {
console.log('Second Listener Executed');
}
// When the event "listenerOne" is emitted, both the above callbacks should
be invoked.
eventEmitter.emit('listenerOne');
// Output
First Listener Executed
Second Listener Executed
Example 02: Registering for the event to be fired only one time
using once.
/**
* Emit Events Once
*/
const events = require('events');
const eventEmitter = new events.EventEmitter();
function listenerOnce() {
console.log('listenerOnce fired once');
}
eventEmitter.once('listenerOne', listenerOnce); // Register listenerOnce
eventEmitter.emit('listenerOne');
// Output
listenerOnce fired once
Example 03: Registering for the event with callback parameters
/**
* Callback Events with Parameters
*/
const events = require('events');
const eventEmitter = new events.EventEmitter();
// Output
status 200 and ok
Event loop is an endless loop, which waits for tasks, executes them
and then sleeps until it receives more tasks.
The event loop executes tasks from the event queue only when the
call stack is empty i.e. there is no ongoing task.
The event loop allows us to use callbacks and promises.
The event loop executes the tasks starting from the oldest first.
Example:
/**
* Event loop in Node.js
*/
const events = require('events');
const eventEmitter = new events.EventEmitter();
// Output
Connection succesful.
Data received succesfully.
Program Ended.
2. setImmdeiate():
Example:
/**
* setImmediate() and process.nextTick()
*/
setImmediate(() => {
console.log("1st Immediate");
});
setImmediate(() => {
console.log("2nd Immediate");
});
process.nextTick(() => {
console.log("1st Process");
});
process.nextTick(() => {
console.log("2nd Process");
});
// Output
Program Started
1st Process
2nd Process
1st Immediate
2nd Immediate
Example:
/**
* Callback Function
*/
function myAsync(a, b, callback) {
setTimeout(function () {
callback(a + b);
}, 100);
}
console.log("Before Asynchronous Call");
// Output
Before Asynchronous Call
After Asynchronous Call
Sum: 30
Node.js events module which emits named events that can cause
corresponding functions or callbacks to be called. Functions ( callbacks )
listen or subscribe to a particular event to occur and when that event
triggers, all the callbacks subscribed to that event are fired one by one in
order to which they were registered.
All objects that emit events are instances of the EventEmitter class. The
event can be emitted or listen to an event with the help of EventEmitter
Example:
/**
* Events Module
*/
const event = require('events');
const eventEmitter = new event.EventEmitter();
// call event
eventEmitter.emit('Sum', 10, 20);
// Output
Total: 30
2. Callbacks:
Example:
/**
* Callbacks
*/
function sum(number) {
console.log('Total: ' + number);
}
// Output
Total: 30
Callback functions are called when an asynchronous function returns its
result, whereas event handling works on the observer pattern. The
functions that listen to events act as Observers. Whenever an event gets
fired, its listener function starts executing. Node.js has multiple in-built
events available through events module and EventEmitter class which are
used to bind events and event-listeners
Example:
/**
* Callback Hell
*/
getData(function(a){
getMoreData(a, function(b){
getMoreData(b, function(c){
getMoreData(c, function(d){
getMoreData(d, function(e){
...
});
});
});
});
});
Example:
/**
* Promises
*/
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Successful!");
}, 300);
});
3. Using Async Await:
Async await makes asynchronous code look like it's synchronous. This has
only been possible because of the reintroduction of promises into node.js.
Async-Await only works with functions that return a promise.
Example:
/**
* Async Await
*/
const getrandomnumber = function(){
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve(Math.floor(Math.random() * 20));
}, 1000);
});
}
addRandomNumber();
/**
* Callback Handler
*/
const Division = (numerator, denominator, callback) => {
if (denominator === 0) {
callback(new Error('Divide by zero error!'));
} else {
callback(null, numerator / denominator);
}
};
// Function Call
Division(5, 0, (err, result) => {
if (err) {
return console.log(err.message);
}
console.log(`Result: ${result}`);
});
1. setTimeout():
This function schedules code execution after the assigned amount of time
( in milliseconds ). Only after the timeout has occurred, the code will be
executed. This method returns an ID that can be used
in clearTimeout() method.
Syntax:
function printMessage(arg) {
console.log(`${arg}`);
}
The setImmediate() method executes the code at the end of the current
event loop cycle. The function passed in the setImmediate() argument is a
function that will be executed in the next iteration of the event loop.
Syntax:
setImmediate(callback, args)
Example:
// Output
// Normal statement in the event loop
// setImmediate() function running...
// setTimeout() function running...
3. setInterval():
The setInterval() method executes the code after the specified interval.
The function is executed multiple times after the interval has passed. The
function will keep on calling until the process is stopped externally or
using code after specified time period. The clearInterval() method can be
used to prevent the function from running.
Syntax:
setInterval(function() {
console.log('Display this Message intervals of 1 seconds!');
}, 1000);
Read Files
index.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
/**
* read_file.js
*/
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
Initiate read_file.js:
node read_file.js
# 7. NODE.JS STREAMS
Example:
const fs = require("fs");
const data = '';
readerStream.on('end',function() {
console.log(data);
});
readerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
Writing to a Stream:
const fs = require("fs");
const data = 'Simply Easy Learning';
writerStream.on('error', function(err) {
console.log(err.stack);
});
console.log("Program Ended");
Piping the Streams:
const fs = require("fs");
console.log("Program Ended");
Chaining the Streams:
const fs = require("fs");
const zlib = require('zlib');
console.log("File Compressed.");
# 8. NODE.JS MULTITHREADING
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
$ node server.js
Master 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started
The worker processes are spawned using the child_process.fork() method,
so that they can communicate with the parent via IPC and pass server
handles back and forth.
The first one (and the default one on all platforms except Windows), is the
round-robin approach, where the master process listens on a port, accepts
new connections and distributes them across the workers in a round-robin
fashion, with some built-in smarts to avoid overloading a worker process.
The second approach is where the master process creates the listen
socket and sends it to interested workers. The workers then accept
incoming connections directly.
As soon as Node js starts, it initializes an event loop. The event loop works
on a queue (which is called an event queue) and performs tasks in FIFO
(First In First Out) order. It executes a task only when there is no ongoing
task in the call stack. The call stack works in LIFO(Last In First Out) order.
The event loop continuously checks the call stack to check if there is any
task that needs to be run. Now whenever the event loop finds any
function, it adds it to the stack and runs in order.
Example:
/**
* Concurrency
*/
function add(a, b) {
return a + b;
}
function print(n) {
console.log(`Two times the number ${n} is ` + add(n, n));
}
print(5);
Here, the function print(5) will be invoked and will push into the call
stack. When the function is called, it starts consoling the statement inside
it but before consoling the whole statement it encounters another function
add(n,n) and suspends its current execution, and pushes the add function
into the top of the call stack.
Now the function will return the addition a+b and then popped out from
the stack and now the previously suspended function will start running
and will log the output to console and then this function too will get pop
from the stack and now the stack is empty. So this is how a call stack
works.
child.kill();
The program above will not quit if my-command spins up some more
processes.
process.kill(-child.pid);
Please note - before pid. This converts a pid to a group of pids for process
kill() method.
Syntax:
Header - Consists of two parts: the type of token (i.e., JWT) and the
signing algorithm (i.e., HS512)
Payload - Contains the claims that provide information about a user
who has been authenticated along with other information such as
token expiration time.
Signature - Final part of a token that wraps in the encoded header
and payload, along with the algorithm and a secret
Installation:
/**
* AuthController.js
*/
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const User = require('../user/User');
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err) return res.status(500).send("There was a problem registering
the user.")
// create a token
let token = jwt.sign({ id: user._id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).send({ auth: true, token: token });
});
});
config.js:
/**
* config.js
*/
module.exports = {
'secret': 'supersecret'
};
The jwt.sign() method takes a payload and the secret key defined
in config.js as parameters. It creates aunique string of characters
representing the payload. In our case, the payload is an object containing
only the id of the user.
Reference:
https://www.npmjs.com/package/jsonwebtoken
Q. How to build a microservices
architecture with Node.js?
Microservices are a style of Service Oriented Architecture
(SOA) where the app is structured on an assembly of interconnected
services. With microservices, the application architecture is built with
lightweight protocols. The services are finely seeded in the architecture.
Microservices disintegrate the app into smaller services and enable
improved modularity.
This file is creating our server and assigns routes to process all requests.
// server.js
The next step is to define the routes for the microservices and then assign
each to a target in the controller. We have two endpoints. One endpoint
called "about" that returns information about the application. And a
"distance" endpoint that includes two path parameters, both Zip Codes of
the Lego store. This endpoint returns the distance, in miles, between
these two Zip Codes.
module.exports = function(app) {
app.route('/about')
.get(controller.about);
app.route('/distance/:zipcode1/:zipcode2')
.get(controller.getDistance);
};
Step 03: Adding Controller Logic
Within the controller file, we are going to create a controller object with
two properties. Those properties are the functions to handle the requests
we defined in the routes module.
module.exports = controllers;
Example:
/**
* myLogger
*/
const express = require("express");
const app = express();
app.use(myLogger);
app.listen(3000);
Note: The next() function is not a part of the Node.js or Express API, but is
the third argument that is passed to the middleware function.
The next() function could be named anything, but by convention it is
always named “next”. To avoid confusion, always use this convention.
Q. Why to use Express.js?
Express.js is a Node.js web application framework that provides broad
features for building web and mobile applications. It is used to build a
single page, multipage, and hybrid web application.
Features of Express.js:
Example:
/**
* Simple server using Express.js
*/
const express = require("express");
const app = express();
/**
* app.js
*/
const app = express();
app.use(bodyParser.json());
app.use("/api/events", events.API);
app.use("/api/forms", forms);
Server network declaration
/**
* server.js
*/
const app = require('../app');
const http = require('http');
1. npm outdated
2. Trace by RisingStack
3. NSP
4. GreenKeeper
5. Snyk
6. npm audit
7. npm audit fix
/**
* Helmet
*/
const express = require('express')
const helmet = require('helmet')
const app = express()
app.use(helmet())
2. JOI module:
To validate user input, one of the best libraries you can pick is joi. Joi is an
object schema description language and validator for JavaScript objects.
/**
* Joi
*/
const Joi = require('joi');
Regular Expressions are a great way to manipulate texts and get the parts
that you need from them. However, there is an attack vector called
Regular Expression Denial of Service attack, which exposes the fact that
most Regular Expression implementations may reach extreme situations
for specially crafted input, that cause them to work extremely slowly.
The Regular Expressions that can do such a thing are commonly referred
as Evil Regexes. These expressions contain: *grouping with repetition,
*inside the repeated group: *repetition, or *alternation with overlapping
(a+)+
([a-zA-Z]+)*
(a|aa)+
4. Security.txt:
app.get('/security.txt', securityTxt({
// your security address
contact: '[email protected]',
// your pgp key
encryption: 'encryption',
// if you have a hall of fame for securty resourcers, include the link
here
acknowledgements: 'http://acknowledgements.example.com'
}))
npm --version
NPM helps to install any Node.js module using the following command.
npm shrinkwrap
It should create new npm-shrinkwrap.json file with information about all
packages you use. Next time, when someone calls npm install, it will
install packages from npm-shrinkwrap.json and you will have the same
environment on all machines.
/**
* File Upload in Node.js
*/
const express = require("express");
const bodyParser = require("body-parser");
const multer = require("multer");
const app = express();
// for text/number data transfer between clientg and server
app.use(bodyParser());
app.listen(3000, function () {
console.log("Listening on port 3000");
});
3. index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multer-File-Upload</title>
</head>
<body>
<h1>MULTER File Upload | Single File Upload</h1>
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/photo"
method = "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Example:
A cookie is a piece of data that is sent to the client-side with a request and
is stored on the client-side itself by the Web Browser the user is currently
using.
Installation:
/**
* cookie-parser
*/
const express = require('express')
const cookieParser = require('cookie-parser')
app.listen(3000)
3. morgan:
Installation:
/**
* Writing logs to a file
*/
const express = require('express')
const fs = require('fs')
const morgan = require('morgan')
const path = require('path')
Nodemon is a utility that will monitor for any changes in source and
automatically restart your server.
Installation:
{
// ...
"scripts": {
"start": "nodemon server.js"
},
// ...
}
5. pm2:
Installation:
https://pm2.keymetrics.io/docs/usage/quick-start/
6. serve-favicon:
Installation:
/**
* serve-favicon
*/
const express = require('express')
const favicon = require('serve-favicon')
const path = require('path')
app.listen(3000)
7. cors:
Installation:
npm install cors
Example:
/**
* Enable CORS for a Single Route
*/
const express = require('express')
const cors = require('cors')
const app = express()
app.listen(8080, function () {
console.log('CORS-enabled web server listening on port 80')
})
8. dotenv:
Installation:
// .env
DB_HOST=localhost
DB_USER=admin
DB_PASS=root
/**
* config.js
*/
const db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
9. fs-extra:
Installation:
/**
* fs-extra
*/
const fs = require('fs-extra')
Installation:
Format Dates
Relative Time
Calendar Time
HTTP methods:
Example:
// users.json
{
"user1" : {
"id": 1,
"name" : "Ehsan Philip",
"age" : 24
},
"user2" : {
"id": 2,
"name" : "Karim Jimenez",
"age" : 22
},
"user3" : {
"id": 3,
"name" : "Giacomo Weir",
"age" : 18
}
}
List Users ( GET method)
Let's implement our first RESTful API listUsers using the following code in
a server.js file −
Following API will show you how to add new user in the list.
const user = {
"user4" : {
"id": 4,
"name" : "Spencer Amos",
"age" : 28
}
}
const id = 2;
/**
* req.params
*/
// GET http://localhost:3000/employees/10
/**
* req.query
*/
// GET http://localhost:3000/employees?page=20
/**
* POST Request
*/
const request = require("request");
The core idea behind promises is that a promise represents the result of
an asynchronous operation. A promise is in one of three different states:
Creating a Promise:
2. The "Secure" attribute can make sure the cookies are sent over
secured channel only.
const obj = {
"userId":1,
"id":1,
"title":"whatever",
"completed":false
}
const options = {
hostname: 'jsonplaceholder.typicode.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
res.on('data', d => {
process.stdout.write(d)
})
})
req.write(data)
req.end()
The architecture of asynchronous explains that the message sent will not
give the reply on immediate basis just like we send the mail but do not
get the reply on an immediate basis. It does not have any dependency or
order. Hence improving the system efficiency and performance. The
server stores the information and when the action is done it will be
notified.
2. Non-Blocking:
Synchronous methods in the Node.js standard library that use libuv are
the most commonly used blocking operations. Native modules may also
have blocking methods. Blocking methods execute synchronously and non-
blocking methods execute asynchronously.
Example:
// Blocking
const fs = require('fs');
const data = fs.readFileSync('/file.md'); // blocks here until file is read
console.log(data);
moreWork(); // will run after console.log
// Non-blocking
const fs = require('fs');
fs.readFile('/file.md', (err, data) => {
if (err) throw err;
console.log(data);
});
moreWork(); // will run before console.log
1. Blocking functions:
Example:
const fs = require('fs');
const data = fs.readFileSync('/file.md'); // blocks here until file is read
console.log(data);
// moreWork(); will run after console.log
The second line of code blocks the execution of additional JavaScript until
the entire file is read. moreWork () will only be called after Console.log
2. Non-blocking functions:
Example:
const fs = require('fs');
fs.readFile('/file.md', (err, data) => {
if (err) throw err;
console.log(data);
});
// moreWork(); will run before console.log
Since fs.readFile() is non-blocking, moreWork() does not have to wait for
the file read to complete before being called. This allows for higher
throughput.
Also, another difference is that when you want to update a resource with
PUT request, you have to send the full payload as the request whereas
with PATCH, you only send the parameters which you want to update.
The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar
to CRUD (Create, Read, Update and Delete) operations in database. We
specify these HTTP verbs in the capital case. So, the below is the
comparison between them.
POST - create
GET - read
PUT - update
DELETE - delete
require('http').METHODS
[ 'ACL',
'BIND',
'CHECKOUT',
'CONNECT',
'COPY',
'DELETE',
'GET',
'HEAD',
'LINK',
'LOCK',
'M-SEARCH',
'MERGE',
'MKACTIVITY',
'MKCALENDAR',
'MKCOL',
'MOVE',
'NOTIFY',
'OPTIONS',
'PATCH',
'POST',
'PROPFIND',
'PROPPATCH',
'PURGE',
'PUT',
'REBIND',
'REPORT',
'SEARCH',
'SUBSCRIBE',
'TRACE',
'UNBIND',
'UNLINK',
'UNLOCK',
'UNSUBSCRIBE' ]
http.STATUS_CODES
require('http').STATUS_CODES
{ '100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'205': 'Reset Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'226': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'425': 'Unordered Collection',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'509': 'Bandwidth Limit Exceeded',
'510': 'Not Extended',
'511': 'Network Authentication Required' }
Making HTTP Requests
const options = {
url: 'https://nodejs.org/file.json',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
States of Promises:
Example:
function logFetch(url) {
return fetch(url)
.then(response => {
console.log(response);
})
.catch(err => {
console.error('fetch failed', err);
});
}
2. Async-Await:
Awaitis basically syntactic sugar for Promises. It makes asynchronous
code look more like synchronous/procedural code, which is easier for
humans to understand.
Putting the keyword async before a function tells the function to return a
Promise. If the code returns something that is not a Promise, then
JavaScript automatically wraps it into a resolved promise with that value.
The await keyword simply makes JavaScript wait until that Promise settles
and then returns its result.
Example:
1. Async/Await:
Syntax
// Normal Function
function add(x,y){
return x + y;
}
// Async Function
async function add(x,y){
return x + y;
}
2. Await:
Async functions can make use of the await expression. This will pause the
async function and wait for the Promise to resolve prior to moving on.
Example:
function doubleAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x * 2);
}, 2000);
});
}
addAsync(10).then((sum) => {
console.log(sum);
});
On the first pass, promises can mitigate the Pyramid of Doom: the
situation where code marches to the right faster than it marches forward.
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
With a promise library, it can flatten the pyramid.
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done();
Reference:
https://www.npmjs.com/package/q
ToDo
These routing methods "listens" for requests that match the specified
route(s) and method(s), and when it detects a match, it calls the specified
callback function.
Syntax:
app.METHOD(PATH, HANDLER)
Where:
a) Route methods:
Example:
Route parameters are named URL segments that are used to capture the
values specified at their position in the URL. The captured values are
populated in the req.params object, with the name of the route parameter
specified in the path as their respective keys.
Example:
Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus()
Set the response status code and send its string representation as
the response body.
d) Router method:
module.exports = router
# 13. NODE.JS CACHING
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
Process is a global object that provides information about the current
Node.js process. Process is a listener function that is always listening to
events.
1. Exit
2. disconnect
3. unhandledException
4. rejectionHandled
node-debug app.js
2. Debugging:
Debugger
Node Inspector
Visual Studio Code
Cloud9
Brackets
3. Profiling:
5. Tracing:
6. Logging:
Caterpillar
Tracer
scribbles
Longjohn
Q. What is a stub?
Stubbing and verification for node.js tests. Enables you to validate and
override behaviour of nested pieces of code such as methods, require()
and npm modules or even instances of classes. This library is inspired on
node-gently, MockJS and mock-require.
Features of Stub:
A use-case can be a file read, when you do not want to read an actual file:
const fs = require('fs');
expect(readFileStub).to.be.called;
readFileStub.restore();
1. Unit Tests
2. Service Tests
3. User Interface Tests
Example:
function validateUser(user) {
username: Joi.string().min(5).max(30).required(),
email: Joi.string().email().min(5).max(50).optional(),
date_of_birth: Joi.date().optional(),
account_status: Joi.string()
.valid("activated")
.valid("unactivated")
.optional(),
}).options({ abortEarly: false });
return JoiSchema.validate(user);
}
const user = {
username: "Deepak Lucky",
email: "[email protected]",
date_of_birth: "2000-07-07",
account_status: "activated",
};
if (response.error) {
console.log(response.error.details);
} else {
console.log("Validated Data");
}
const encrypted =
'4ce3b761d58398aed30d5af898a0656a3174d9c7d7502e781e83cf6b9fb836d5';
const decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
Q. What is REPL?
REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to
Shell (Unix/Linux) and command prompt. Node comes with the REPL
environment when it is installed. System interacts with the user through
outputs of commands/expressions used. It is useful in writing and
debugging the codes. The work of REPL can be understood from its full
form:
Read: It reads the inputs from users and parses it into JavaScript
data structure. It is then stored to memory.
Eval: The parsed JavaScript data structure is evaluated for the
results.
Print: The result is printed after the evaluation.
Loop: Loops the input command. To come out of NODE REPL, press
ctrl+c twice
Simple Expression
$ node
> 10 + 20
30
> 10 + ( 20 * 30 ) - 40
570
>
Q. What does the runtime environment
mean in Node.js?
The Node.js runtime is the software stack responsible for installing your
web service's code and its dependencies and running your service.
runtime: nodejs10
The runtime environment is literally just the environment your application
is running in. This can be used to describe both the hardware and the
software that is running your application. How much RAM, what version of
node, what operating system, how much CPU cores, can all be referenced
when talking about a runtime environment.
For example, when we work on a project and there are production and
development environments. We don't need to use caching in the
development env. So we set
NODE_ENV=development
and use the code below
// Sample usage
Installation:
npm install memcached
Setting up the client:
/**
* Memcached
*/
const Memcached = require('memcached');
// all global configurations should be applied to the .config object of the
Client.
Memcached.config.poolSize = 25;
For the checksum generation, we can use node crypto() module. The
module uses createHash(algorithm) to create a checksum (hash) generator.
The algorithm is dependent on the available algorithms supported by the
version of OpenSSL on the platform.
Example:
console.log(hashPwd); //ef5225a03e4f9cc953ab3c4dd41f5c4db7dc2e5b