Nodejs Notes
Nodejs Notes
js
===================================
Variables
Scopes
Functions
Arrow Function
this operator
Loops
String
Array
fetch()
ES-6 and beyond
(class,module,rest,spread,promise,async await)
Node.js Syllabus
================
-Node.JS - Introduction, Advantages
-Traditional Web Server Model, Node.js Process Model
-Local Environment SetUp
-Node.js Console - REPL
-NPM , NPX , NVM
-Modules: Core, Local , 3rd party
-Global Objects
-File System
-Debugging Node JS Application
-Buffer & Streams
-Events (Event Loop,Event Emitter)
-Creating web server & Handling http requests (HTTP)
-Express Framework-routes
-NodeJS & MongoDB Connection
-Mongoose,graphQL
-Template Engines (Jade/Pug, vash, EJS, handlebars)
-Redis (Caching)
-Swagger (API Documentation)
-Unit testing (Mocha, Jasmine)
-JWT
Projects
========
-CRUD HTTP Module
-CRUD ExpressJS
-GraphQL
-Template Engine
-Server Side Validation
-Image Upload (express-file-uploader)
-Image Upload (Formidable)
-NodeEmailer (Send Email)
-Chat Application (Socket.io)
-JWT Token
-Swagger
-Unit testing
javascript Engines:
V8 - is developed by Google , Google Chrome.
SpiderMonkey - is developed by Mozilla , Firefox.
JavaScriptCore - is Apple's engine for its Safari browser.
Chakra - is the JavaScript engine of the Internet Explorer browser.
Browser Node.js
======================================================
-DOM (document) -No DOM
-Window -No Window (global)
-Cookies -No Cookies
-Offline Storage -No Offline Storage
-No FileSystem -FileSystem
-Database Interaction(No) -Database Interaction(yes)
-Client Apps/ UI -Server side Apps / Back-End
-Consume APIs -Develop APIs
JS Code --> V8 --> Parsing --> Abstract Syntax Tree --> ByteCode --> Machine
Code --> Runs On CPU
-All the user requests are handled by a single thread and all the I/O work or
long running job is performed asynchronously for a particular request.
-single thread(Event Loop) doesn't have to wait for the request to complete and
is free to handle the next request.
-When asynchronous I/O work completes, worker thread informs event
loop,eventloop sends the response back to client.
-Internally, Node.js uses libuv for the event loop which in turn uses internal
C++ thread pool to provide asynchronous I/O.
https://cdn.buttercms.com/0Nh1yR6SSPwqnsKYSfHa
https://www.scholarhat.com/tutorial/nodejs/nodejs-vs-other-server-side-
frameworks
NodeJs vs Others
================
-A common task for a web server can be to open a file on the server and return
the content to the client.
REPL
====
-REPL stands for Read-Eval-Print-Loop.
R - Reads user's input
E - Evaluates the expression
P - Prints the result
L - Loops the above things until user kills the process
-Node.js comes with virtual environment called REPL.
-it is similar to Shell in Linux or command prompt in windows where
a command is entered and the system responds with an output in an interactive
mode
-It is a quick and easy way to test simple Node.js/JavaScript code.
-To launch the REPL (Node shell), open command prompt and type 'node'.
-If you need to write multi line JavaScript expression or function then just
press Enter.
(The REPL terminal will display three dots (...), it means you can continue on
next line)
-We can execute an external JavaScript file by writing 'node <Filename>'.
-assign the result of the most recently evaluated expression to the special
variable _ (underscore)
a = 10; b = 20; a+b;
sum = _; console.log(sum);
-To Open REPL in editor mode , use .editor
-To Exit REPL type .exit
-if you press the tab key the REPL will try to autocomplete what you wrote to
match a variable you already defined or a predefined one.
-Used For Exploring node objects ( os, fs , http)
fs (enter)
Assignment:
-Ask user to enter 2 numbers and 1 operator(+ - * /)
-perform arithmetic operation on those 2 numbers
Note: Handle edge cases also (user should pass arguments, if not show error
message)
Minimist
========
-The best way to deal with key:value arguements is by using the 'minimist'
library.
const minimist = require('minimist');
const argArr = process.argv.slice(2);
const argObj = minimist(argArr);
console.log(argObj)
-use double dashes before each argument name
node app.js --name=sanjay --add=bangalore
Note: process module does not need a "require", it's defaultly available.
Assignment:
-Build a calculator using minimist
node calculator.js --num1 10 --num2 5 --operation add
VS Code Extensions
==================
vscode-icons
prettier
tab nine
thunderclient
ESLint
-npm install
install all the modules as specified in package.json
-Run a Script
npm run <script-name>
npm i nodemon --> helps during development and production
dependencies
npm i nodemon --save --> helps during development and production
dependencies
npm i nodemon --save-dev --> helps during development not in production(-D)
npm i nodemon --no-save --> installs but does not add the entry to the
package.json file dependencies
npm i nodemon --save-optional --> installs and adds the entry to the
package.json file optionalDependencies
npm i --no-optional --> will prevent optional dependencies from being installed
yarn --version
yarn --help
yarn init -y
yarn add minimist
yarn add mocha --dev
yarn add minimist@latest
yarn add minimist@2.3.1
yarn install
yarn install --production
yarn install --offline ( trigger an error if any required dependencies are not
available in local cache)
yarn remove minimist
yarn upgrade
yarn run [script-name]
yarn outdated
yarn audit (runs a security audit)
Package.json
============
-Contains the metadata of the project.
-Helps NPM to understand how the project should be handled along with its
dependencies.
-package.json files contain the below information.
project name,
version,
homepage,
description,
author,
keywords
scripts
dependencies
devdependencies
optionaldependencies etc.
-package.json file is normally located at the root directory of a Node.js
project.
package.json VS package-lock.json
===================================
-package.json maintains only the main packages's information.
"cors": "^2.8.5"
"bootstrap" : "^5.2.1"
-package-lock.json containes the exact version.
"bootstrap" : "5.3.2" (npm update bootstrap)
-package-lock.json maintains main packages's information + nested-packages
information
"node_modules/cors": {
"dependencies": {
"object-assign": "^4",
"vary": "^1"
}
-package.json lists the required dependencies and their version ranges, but not
the exact versions to be installed.
-package-lock.json is used to ensure that the same dependencies are installed
across different environments and prevent conflicts due to different versions
being installed.
NPX
===
NPX : Node Package Executer (used to execute Node.js packages)
-Run Packages without installing them.
-When you install NPM version 5.2.0 or higher, get NPX installed
-we can install npx using the below command
npm i -g npx
-npx helps us avoid versioning, dependency issues and installing unnecessary
packages that we just want to try out.
-npx helps running utility tools without installation (eslint, mocha)
npx eslint .
npx mocha
-ex:npx create-react-app my-sample-react-app
npx nodemon file1.js
npx nodemon file1.js -y
Nodemon
=======
-Nodemon is a utility that will monitor for any changes in your source and
automatically restart your server.
-Nodemon can be installed using NPM.
ex:- npm i -g nodemon
-Nodemon can be used without installing also, using npx
npx nodemon file1.js
-nodemon help
nodemon -h
nodemon --help
-Just use nodemon instead of node to run your code, your process will
automatically restart when your code changes
ex:- node file1.js (server won't be re-started when code is changed)
nodemon file1.js (server gets re-started when there is a code change)
npx nodemon file1.js (server gets re-started when there is a code
change)
-The 'node_modules' folder is ignored by default by nodemon.
-You can restart the process at any time by typing 'rs' and hitting enter.
Note:
__dirname : __dirname is not defined in ES module scope
global globalThis
===============================================================
Node.js Specific-Yes Node.js Specific-No(Universal across
environments)
Standardized-No Standardized-Yes (Standardized by
ECMAScript)
Only available in Node.js Works in Node.js, browsers, and more
Access Node.js-specific globals Access global objects in any
environment
This
====
-The behavior of the this keyword depends on the context in which it is used.
-The value of this can vary between global scope, functions, and object methods,
and it behaves differently in different scenarios, including strict mode,
classes, and modules.
2. Inside Functions
-in Normal Mode:
a. this value inside a regular/normal function is 'global Object'.
b. this value inside an arrow function is {} (module.exports)
-in strictmode, this value inside a function is undefined.
4. Inside Classes
-In classes, this refers to the instance of the class.
Event Loop
==========
-The event loop in Node.js is a mechanism that allows asynchronous tasks to be
handled efficiently without blocking the execution of other operations.
-handles asynchronous operations by executing callbacks in a non-blocking
manner.
-It executes Synchronous code first,then processes asynchronous operations.
-Delegates heavy tasks like I/O operations, timers, and network requests to the
libuv library.
-
-Event loop's order of operations:
1. timers: Executes setTimeout() and setInterval() callbacks whose delay has
expired
2. I/O Pending CallBacks: executes I/O-related callbacks that were deferred
from the previous loop cycle.
3. idle, prepare: Used internally by Node.js and is not directly used by user
applications
4. poll: Retrieves new I/O events(File reading,Http) and executes their
callbacks
5. check: Executes setImmediate() callbacks
6. close callbacks: Executes close event callbacks like socket.on('close',
()=>{})
NodeJs Timers
=============
-setImmediate() is designed to execute a script once the current poll phase
completes.
setImmediate() is useful when you want to execute a callback after I/O tasks in
the current event loop iteration but before timers in the next iteration
-if we run setImmediate() & setTimeout() which is not within an I/O cycle (i.e.
the main module), the order in which the two timers are executed is non-
deterministic.
-However, if you move the two calls within an I/O cycle, the immediate callback
is always executed first.
NodeJs Modules
==============
-A way of encapsulating code in to separate logical units.
-Module:A set of properties and functions we want to include in our application.
-In Node.js module system, each file is treated as a separate module.
-Node.js includes three types of modules:
1. Core(Built-in) Modules (os,fs,http,path,url,crypto)
2. Local(Custom) Modules (created locally in our application)
3. Third Party(External) Modules (can be installed using NPM, and can be
used) ex:-minimist,express,mongoose,lodash,moment,chalk,cors,axios
Core Modules:
-------------
os-Get OS information
fs-work with the file system
path-handles path elegantly
url-url module includes methods for URL resolution and parsing.
querystring-querystring module includes methods to deal with query string.
process -
http-launch a server,send requests
https-launch a SSL server
events-working with events
util-util module includes utility functions useful for programmers.
Local(Custom) Modules
=====================
-Node.js has two types of modules:
1. ES modules (.mjs)
2. CommonJS modules (.cjs)
-By default, Node.js treats JavaScript as CommonJS modules. But we can tell
Node.js to treat JavaScript code as ES modules.
-Node.js will treat the following files as ES modules:
a.Files ending in .mjs
b.if "type": "module" is set in package.json
Module Systems
==============
1. CommonJS
module.exports = {member1,member2};
const member1 = require('Library/file name');
2. ECMASCRIPT
export member1;
export default member2;
import DefaultMember , {Namedmember} from 'file'
External Modules(minimist,chalk,validator,lodash,moment)
----------------
1. Installing an npm Module
npm install validator
2. Importing an npm Module
const validator = require('validator')
console.log(validator.isURL('https://www.google.co.in/')) // true
console.log(validator.isEmail('abc@gmail.com')) // true
Node.js OS Module
=================
-The OS module provides information about the computer's operating system.
Node.js fs module
=================
-The fs module provides a lot of very useful functionality to access and
interact with the file system.
-There is no need to install it. Being part of the Node.js core, it can be used
by simply requiring it. and have access to all its methods.
ex:
const fs = require('fs');
fs.readFile(fileName [,options], callback) Reads existing file.
fs.writeFile(filename, data[, options], callback) Writes to the file. If file
exists then overwrite the content otherwise creates new file.
fs.open(path, flags[, mode], callback) Opens file for reading or writing.
fs.rename(oldPath, newPath, callback) Renames an existing file.
fs.chown(path, uid, gid, callback) Asynchronous chown.
fs.stat(path, callback) Returns fs.stat object which includes important file
statistics.
fs.link(srcpath, dstpath, callback) Links file asynchronously.
fs.unlink(path, callback); Delete a file.
fs.symlink(destination, path[, type], callback) Symlink asynchronously.
fs.rmdir(path, callback) Renames an existing directory.
fs.mkdir(path[, mode], callback) Creates a new directory.
fs.readdir(path, callback) Reads the content of the specified directory.
fs.utimes(path, atime, mtime, callback) Changes the timestamp of the file.
fs.exists(path, callback) Determines whether the specified file exists or
not.
fs.access(path[, mode], callback) Tests a user's permissions for the specified
file.
fs.appendFile(file, data[, options], callback) Appends new content to the
existing file.
file encoding
=============
-Both fs.readFileSync() and fs.readFile() take an optional argument encoding.
-while reading a file, a string will be returned if character encoding is
specified.
-while reading a file, a buffer will be returned if character encoding is not
specified.
ex: bufferData = fs.readFileSync("./customer.json");
stringData = fs.readFileSync("./customer.json", "utf8");
Note: UTF-8 is an encoding system for Unicode. It can translate any Unicode
character to a matching unique binary string.
JSON
====
-Node has some built in utilities that make it easy to read and write JSON
files.
-The simplest way to read a JSON file is to require it.
ex: const config = require("./config.json");
-But reading JSON files with require has its downsides.
-The file will only be read once; requiring it again returns the cached data
from the first time require was run.
-This is fine for loading static data on startup (like config data). But for
reading a file that changes on disk, we need to manually read the file using
fs.readFile()
const jsonString = fs.readFileSync("./customer.json","utf8");
const customer = JSON.parse(jsonString);
join() vs resolve()
===================
-join() concatenates(joins) the path segments.
-resolve() creates an absolute path from the root.
-Both methods will normalize the paths i.e. they treat .. as we normally use
them when navigating in the folder structure.
https://www.scaler.com/topics/nodejs/path-module-in-node-js/
-characters such as "/", "?", "#", ":", "@", "&", "=", "+", "$", and ",". When
these characters need to be included in a URL as data rather than as part of the
URL syntax, they must be percent-encoded / escaped.
-For instance, the character "@" is encoded as "%40", and the character "#" is
encoded as "%23".
Process Module
==============
-Process Module provides the env property which hosts all the environment
variables that were set at the moment the process was started.
Note: process does not need a "require", it's automatically available.
-If you have multiple environment variables in your node project, create an .env
file in the root directory of project, and then use the 'dotenv' package to load
them during runtime.
.env file
USER_ID="239482"
USER_KEY="abcd"
NODE_ENV="development"
PORT=1234
-npm install dotenv
require('dotenv').config();
process.env.USER_ID; // "239482"
process.env.USER_KEY; // "abcd"
process.env.NODE_ENV; // "development"
-How to find which version of V8 ships with a particular version of Node.js?
node -p process.versions.v8
-process.nextTick() : invoke this function at the end of the current operation,
before the next event loop tick starts
-This function defers the execution of a callback function until the next Event
Loop Iteration.
-Every time the event loop takes a full trip, we call it a tick.
-setTimeout(() => {}, 0) will execute the function at the end of next tick, much
later than when using nextTick() which prioritizes the call and executes it just
before the beginning of the next tick
Note: if the same variable is defined in the environment and in the file, the
value from the environment takes precedence.
execFile()
execute a file (bat/sh)
spawn()
launch a new process and interact with that process
when the command we want to run can output a large amount of data
fork()
-Utilizes multi-core CPUs efficiently.
-Isolates processes, preventing one failure from affecting others.
-Handles high traffic loads better than a single-threaded approach.
-communication channel is established to the child process when using fork, so
we can use the send() function on the forked process along with the global
process object itself to exchange messages between the parent and forked
processes.
-ChildProcess will have an additional communication channel built-in that allows
messages to be passed back and forth between the parent and child
HTTP Module
===========
-HTTP module can create an HTTP server.
-Receives the request from client & returns response back to the client.
-headers, URL, method and body data can be collected from request objects.
-Make routing decisions based on URL and/or other data in request objects.
-Send headers, HTTP status codes and response data via response objects.
response.setHeader('Content-Type', 'text/html');
response.writeHead() should be called first when initiating a response, allows
us to set up the HTTP response code and headers we are sending back.
response.write(chunk[, encoding][, callback]) allows us to send a chunk of data
as part of our response.
Note:Unless you change the path to your favicon in an HTML document, browsers
will (usually) make a request to the /favicon.ico path in order to get the
favicon of your server.
HTTP Methods
============
https://testfully.io/blog/http-methods/
200 OK
201 Created
202 Accepted accepted for processing,processing has not been finished
204 No Content successfully fulfilled the request, there is no available
content
205 ResetContent the user should reset the document that sent this request
206 Partial Content
300 MultipleChoices request has multiple possible responses, user should choose
one
301 MovedPermanently the target resource has been assigned a new permanent URL
400 BadRequest the server could not understand the request because of invalid
syntax.
401 Unauthorized client needs to authenticate itself to get access.such as a
username and password.
402 Payment Required
403 Forbidden the client has been authenticated, but it does not have the
necessary permissions to access the requested resource
404 NotFound could not locate the requested resource. Page/URL not found
405 MethodNotAllowed the method has been disabled and can not be used(only
get ,not post,put)
406 NotAcceptable if a client requests a response in JSON format by including
"Accept: application/json" in the request header, but the server can only
provide data in XML format
407 Proxy Authentication Required
408 RequestTimeout server did not receive a complete request in the time that
it prepared to wait
409 Conflict
Route-Parameter
===============
1. PathParam
-passed after /
ex:- /productDetails/101
-Need to define in the route
ex: app.get('users/:id')
-If defined than need to pass in url
-only 1 value can be passed
2. QueryParam
-passed after ?
ex: /search?searchWord=skybag&filter=something
-No Need to define in the route
ex: app.get('users')
-not complusory to pass
-used to pass multiple values.
NodeJS Buffers
==============
-Buffer represents a fixed-length sequence of bytes.
-Buffer is a built-in object used to handle binary data directly, without
needing to convert it into string or other format.
-to preocess raw binary data, such as reading data from file handling network
communication.
-Buffers are used with readable & writable streams for efficient data handling,
especially for large files.
-Buffers are essential when dealing with image data. Images are typically
handled as binary data while sending over a network.
Node.js Streams
===============
-Streams are objects that let you read data from a source or write data to a
destination in continuous fashion.
-When we try to read a file, the contents of the file is read and all the
content gets saved in memory
-Streams read chunks of data piece by piece, processing its content without
keeping it all in memory.
Express.JS
==========
-Express.js is a web application framework for building RESTful APIs with
Node.js.
-a framework is a set of helper functions,tools and rules that help us to build
our application.
-It provides various features that make web application development fast and
easy which otherwise takes more time using only Node.js.
-Alternatives to Express.js are 'NestJS' , 'LoopBack','koa','sails.js'
-NestJS : A progressive Node.js framework for building efficient, reliable and
scalable server-side applications.
https://expressjs.com/en/starter/examples.html
Advantages of Express.js
========================
-Makes Node.js web application development fast and easy.
-Easy to configure and customize.
-Allows to define routes of your application based on HTTP methods and URLs.
-Includes various middleware modules which you can use to perform additional
tasks on request and response.
-Easy to integrate with different template engines like Jade, Vash, EJS etc.
-Allows to define an error handling middleware.
-Easy to serve static files and resources of your application.
-Allows to create REST API server.
-Easy to connect with databases such as MongoDB, Redis, MySQL.
How to use Express
==================
1. import express
const express = require('express')
2. create an instance of express.
const app = express()
3. use methods
app.get(route, callback)
app.post(route, callback)
Express Methods
===============
app.get()
app.post()
app.put()
app.patch()
app.delete()
app.listen()
app.use()
app.all()
app.use() vs app.get()
======================
-app.use() can handle all type of HTTP requests(GET,POST,PUT,DELETE)
-app.use() is generally used for introducing middlewares.
app.use(express.json()); // express.json() is middleware
-app.get() is only for handling GET HTTP requests.
app.get('/users', (req, res) => {
res.send('all users')
})
app.use() vs app.all()
======================
app.use() will only see whether url starts with specified path.
app.all() will match the complete path.
Response methods
================
The methods on the response object (res) in the following table can send a
response to the client, and terminate the request-response cycle. If none of
these methods are called from a route handler, the client request will be left
hanging.
Method Description
res.send() Send a response of various types. (Buffer / JSON / HTML / String)
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.sendFile() Send a file as an octet stream.
res.download() Prompt a file to be downloaded.
res.sendStatus() Set the response status code and send its string
representation as the response body.
Status() vs sendStatus()
========================
res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(201); // equivalent to res.status(201).send('CReated')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server
Error')
Express Routing
===============
-Routing refers to how an application’s endpoints (URIs) respond to client
requests.
-Route paths, in combination with a request method, define the endpoints at
which requests can be made.
-Route paths can be strings, string patterns, or regular expressions
Examples:
app.get('/ab?cd'); // will match acd and abcd
app.get('/ab+cd'); // will match abcd, abbcd, abbbcd
app.get('/ab*cd'); // will match abcd, abxcd, abRANDOMcd, ab123cd
app.get('/ab(cd)?e'); // will match /abe and /abcde
app.get(/.*fly$/); // will match butterfly and dragonfly, but not butterflyman,
dragonflyman
app.all('*',(req,res)=>{
res.status(404).send('No such page found')
});
Express PathParam & QueryParam
==============================
1. Path-Param
ex:- /users/101
const userId = req.params.userId;
2. Query-param
ex:- /search?searchWord=skybag&filter=something
const {searchWord,filter} = req.query;
express.Router()
================
-express.Router() creates a new router object that can handle requests in a
modular and organized way
Middlewares
===========
-Middlewares in ExpressJS are functions that can modify Request and Response
objects.
-Middleware functions can handle logging, authentication, and input validation
before passing control to the next handler.
-
without middleware :
request => Route => Response
with middleware :
request => middleware1 => middleware2 => Route => Response
https://www.turing.com/kb/building-middleware-for-node-js
https://expressjs.com/en/guide/using-middleware.html
https://expressjs.com/en/resources/middleware/body-parser.html
Q.How to run a middleware for all the routes for a router object
const userRouter = express.Router();
userRouter.use(logger);
logger middleware
==================
const logger = (req, res, next) => {
console.log(`URL:${req.url} , method:${req.method} , Time:${new
Date().toLocaleTimeString()}`)
next();
}
authenticate middleware
=====================
const authenticate = (req, res, next) => {
const token = req.headers['authorization'];
if (!token || token !== 'mysecrettoken') {
res.status(401).json({ message: 'Unauthorized' });
} else {
next(); // User is authenticated, proceed to next middleware or route
handler
}
};
Error handler
=============
let myErrorHandler = (err, req, res, next) => {
const errorStatus = err.status || 500;
const errorMessage = err.message || 'Something went wrong, Try again!';
res.status(errorStatus).json({
status: errorStatus,
message: errorMessage,
stack: err.stack,
success: false,
});
};
Note : this should be present after all the routes & before app.listen(5000)
Body-parser
===========
-parse the body of requests which have payloads attached to them.
-Parse incoming request bodies(formData) in a middleware before handlers are
invoked.
-extracts the body portion of an incoming request & exposes it on req.body.
-parses the data submitted using HTTP POST request.
npm install body-parser --save
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Note: ExpressJS provides its inbuilt functions for parsing request body
app.use(express.json());
app.use(express.urlencoded());
cookie-parser
=============
-To Read cookie information from client.
-It parses Cookie header and populate req.cookies with an object keyed by cookie
names.
-To Store cookies in client, cookie-parser is not required
-cookie-parser is required while reading cookie information from browser.
ex:
const createEmailChain = () => body('email').isEmail();
app.post('/login', createEmailChain(), handleLoginRoute);
app.post('/signup', createEmailChain().custom(checkEmailNotInUse),
handleSignupRoute);
tsconfig.json
-------------
{
"compilerOptions": {
"lib": [
"es6"
],
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "dist",
"resolveJsonModule": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"sourceMap": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
Use a Logging Service to track and store errors in production
=============================================================
-To improve error management, we can integrate logging services
-Winston or Morgan can be used for logging error details to external files or
monitoring services.
-These are helpful for production environments
Morgan
======
-Morgan is a popular HTTP request logger middleware for Node.js.
-Alternatives Packages to morgan are : Winston / Bunyan / Pino
-It simplifies the process of logging HTTP requests in a Node.js application by
automatically generating logs for incoming requests.
-Morgan provides various logging formats and options, allowing developers to
customize the logging output according to their requirements.
-Logging formats : combined / common / short / tiny / dev
1. npm i morgan
2. const morgan = require('morgan');
app.use(morgan('tiny'));
app.use(morgan('dev'));
app.use(morgan(':method :url :status :res[content-length] - :response-time
ms'));
Winston
=======
-winston is a logging library with support for multiple transports(console,
file)
CORS(Cross-Origin-Resource-Sharing)
====
-CORS (Cross-Origin Resource Sharing) is a security feature implemented by web
browsers to prevent harmful cross-origin requests.
-It blocks requests made from one origin(domain/protocol,port) to another origin
unless explicitly allowed by the server.
-CORS allows servers to specify which domains can access their resources/API.
Key Features:
-Prevents unauthorized cross-origin requests:
By default, browsers block requests made from one domain to another (a
different origin). The cors middleware enables specific domains or all domains
to access your resources.
-Customizable origin policies:
We can whitelist specific origins, methods, and headers that are allowed
to interact with your server.
const corsOptions = {
origin: 'https://example.com', // Allow only this domain
methods: ['GET', 'POST'], // Allow specific HTTP methods
allowedHeaders: ['Content-Type', 'Authorization'], // Allow specific headers
}
app.use(cors(corsOptions)); // allow only certain origins, methods & headers
Default Configuration
corsOptions = {
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}
https://www.npmjs.com/package/cors
CURL
====
-Client URL
-A command-line tool used for making HTTP requests & testing network
connections.
-Most systems come with cURL pre-installed
Helmet
======
-It Helps to secure Node.js application by setting several HTTP headers.
-automatically adds or removes HTTP headers to comply with web security
standards.
-It protects against XSS, clickjacking, MIME sniffing, and other
vulnerabilities.
-Express applications do not come with security HTTP headers out of the box.
-Without Helmet, default headers returned by Express expose sensitive
information and make your Node.js app vulnerable to malicious actors
curl http://localhost:3000/
curl http://localhost:3000/ --include
Or
use an HTTP client such as Postman to inspect the HTTP headers of the response
without Helmet
==============
-response header should have X-Powered-By header. As with all headers that begin
with X-, it is a non-standard header. X-Powered-By indicates the name and
version number of the framework or library used by the server to generate the
HTTP response.
-we should never give attackers details about our tech stack.
https://securityheaders.com/
Events
======
-Node.js allows us to create and handle custom events easily by using events
module.
-Event module includes EventEmitter class which can be used to raise and handle
custom events.
-An event can be raised/triggered using emit(). in emit() First parameter is the
name of the event as a string and then arguments.
ex: emit(eventName)
emit(eventName, arg1 , arg2)
-An event can be emitted with zero or more arguments.
-We can specify any name for a custom event in the emit() function.
-use addListener() / on() to subscribe/listen an event.
-Event names should be camel-cased strings but any valid name should be fine.
-Listeners should not return any value , Any values returned by the called
listeners are ignored and will be discarded.
-The EventEmitter calls all listeners synchronously in the order in which they
were registered.
-This ensures the proper sequencing of events and helps avoid race conditions
and logic errors.
When appropriate, listener functions can switch to an asynchronous mode of
operation using the setImmediate() or process.nextTick() methods:
-Using the eventEmitter.once() method, it is possible to register a listener
that is called at most once for a particular event.
-Once the event is emitted, the listener is unregistered and then called.
-To render template files, set the following application properties, in app.js
app.engine('pug', require('pug').__express)
app.set('views', './views')
app.set('view engine', 'pug')
https://expressjs.com/en/guide/using-template-engines.html
MongoDB
=======
-it stores data in the collections as JSON based documents and does not enforce
schemas.
-UnStructured data. structure of every document must not be the same.
-It does not have tables, rows, and columns as other SQL (RDBMS) databases.
-RDBMS (Database,Table,Row,Column)
MongoDB(Database,Collection,Document,Field)
-indexing , schemaless , Replication, Scalability, Performance, High
Availability.
-No SQL databases - MongoDB, cassandra, Amazon Dynamo DB, couchbase, redis.
Relational databases - MySql , Oracle , PostgreSQL
Sql MongoDB
===================
Database Database
Table Collection
Row Document
Column Field
Select find
Insert Insert
Update Update
Delete Remove
MongoDB Local
=============
1. download and install (MongoDB Community Server)
https://www.mongodb.com/try/download/community
(OR)
https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-6.0.5-signed.msi
The Below Points are optional if we want to access our database in MongoDB
Compass
2. Go to the path where MongoDB is installed,and run 'mongod.exe'
By default it is "C:\Program Files\MongoDB\Server\6.0\bin"
4. Expect Error as the data directory is not set
"{"error":"NonExistentPath: Data directory C:\\data\\db\\ not found"
5. create folder 'c:\data\db'
6. run 'mongod.exe'
7. set path for mongo-server(To start mongodb from any path)
C:\Program Files\MongoDB\Server\6.0\bin
https://treehouse.github.io/installation-guides/mac/mongo-mac.html
https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/
MongoDB Compass
===============
-MongoDB Compass is a graphical interface to interact with the MongoDB
-Manage MongoDB data without writing complex shell commands
1. Download and install MongoDB Compass (It comes along with mongoDB)
https://www.mongodb.com/try/download/compass
2. open mongoDB Compass GUI
3. Enter mongoDB Connection String
mongodb://localhost:27017 (OR)
mongodb://127.0.0.1:27017
mongodb://0.0.0.0:27017
MongoDB Queries/Commands
========================
https://www.geeksforgeeks.org/mongodb-tutorial/
db.employees.find().sort({sal:1}) //asc
db.employees.find().sort({sal:-1}) //desc
db.employees.find().count()
db.employees.countDocuments({salary:13001});
db.employees.find().limit(2)
db.employees.find().sort({sal:-1}).skip(2).limit(1)
db.employees.distinct('eid'); // ['e101','e102']
db.employees.updateOne({eId:'e102'},{$inc:{sal:100}}); // increment
db.employees.updateOne({eId:'e102'},{$inc:{sal:100},$set:{age:35}}); //
increment sal + update age
Q. find() vs findOne()
======================
findOne() - if query matches, first document is returned, otherwise null.
findOne() never returns a cursor
cursor methods cannot be used with the returned value of
findOne()
find() - no matter the number of documents matched, a cursor is returned, never
null.
MongoDB Datatypes
=================
-String
-Boolean
-Numebr
Int32
Long
Double
-Date
Date() : returns the current date as a string
new Date() : returns a Date object
ISODate() : returns a Date object using the ISODate()
-ObjectId : new ObjectId()
A special type used to uniquely identify documents in a collection
-Timestamp : new Timestamp()
Timestamp{ "t": <integer>, "i": <integer> } Used for ordering when there are
multiple operations within a given second
$text
=====
db.articles.find( { $text: { $search: "coffee" } } )
db.articles.find( { $text: { $search: "Coffee", $caseSensitive: true } } )
db.articles.find( { $text: { $search: "bake coffee cake" } } )
bake / coffee / cake
db.articles.find( { $text: { $search: "\"coffee shop\"" } } )
coffee shop
db.articles.find( { $text: { $search: "\'coffee shop\' \'Cafe con Leche\'" } } )
Or
$where
db.table3.find( { $where: function() { return (this.english == this.science) }})
Array
$addToSet: Adds distinct elements to an array
$pop: Removes the first or last element of an array
$pull: Removes all elements from an array that match the query
$push: Adds an element to an array
db.employees.deleteMany({name:'sanjay',name:'geeta',name:'sameer'})
-only sameer will be deleted, first 2 conditions are ignored
Managing Indexes
================
-Without indexes, MongoDB must scan every document of a collection to select
those documents that match the query statement.
-This scan is highly inefficient and require MongoDB to process a large volume
of data.
Basic Index:
db.users.find({_id:1});
-by default MongoDB creates an index on _id field for every collection.
Compound Indexes:
-Compound indexes collect and sort data from two or more fields
ex:db.users.createIndex({age:1,status:1})
MultiKey Index:
-when one of the indexed fields is an array. MongoDB automaticaaly creates a
multikey index if we index a field that contains an array
db.users.createIndex({tags:1})
Aggregation Operations
======================
-Aggregation operations process multiple documents and return computed results
-Used to:
1. Group values from multiple documents together.
2. Perform operations on the grouped data to return a single result.
3. Analyze data changes over time.
Aggregation Pipelines
======================
-An aggregation pipeline consists of one or more stages that process documents.
-Each stage performs an operation on the input documents. For example, a stage
can filter documents, group documents, and calculate values.
-The documents that are output from a stage are passed to the next stage as
input.
-An aggregation pipeline can return results for groups of documents. For
example, return the total, average, maximum, and minimum values.
-db.collectionName.aggregate(pipeline, options)
input --> $match --> $group --> $sort --> output
ex: db.cities.aggregate([
{$match:{"continent":"Africa"}}
])
Assignment
==========
1. Find distinct salaries in asccending order.
2. Find the 3rd highest salary in the employee table.
3. Find the employees whose DOB is today's date.
4. increase the salary of every employee by 500.
5. change the 'gender' of every employee (male-->female,female-->male)
6. add 'mr.' before the names of all male employees
Assignment Solutions
====================
1.db.employees.distinct('salary').sort((a,b)=>a-b);
2.db.employees.find().sort({'salary':-1}).skip(2).limit(1);
3.db.employees.find({
$expr: {
$and: [
{ $eq: [{ $dayOfMonth: "$dob" }, { $dayOfMonth: new
Date() }] }, // day
{ $eq: [{ $month: "$dob" }, { $month: new Date() }] }
// month
]
}
});
4.db.employees.updateMany({},{ $inc: { salary: 500 } });
// For Decrement - $inc: { salary: -500 }
5.db.employees.updateMany({},[ {$set:{gender:{$cond:{
if: { $eq: ['$gender', 'male'] },
then: 'female',
else: 'male'
}}}} ]);
6.db.employees.updateMany(
{ gender: "male" },
[
{
$set: {
name: {
$concat: [ "Mr. ", "$name" ]
}
}
}
]
);
Views
======
-A MongoDB view is a read-only queryable object whose contents are defined by an
aggregation pipeline on other collections or views.
db.createView(
"firstYears",
"students",
[{ $match: { year: 1 } }]
)
db.firstYears.find({}, { _id: 0 } )
Join In MongoDB
===============
-use $lookup stage in the aggregation pipeline to perform joins between
collections
{
"$lookup": {
"from": "foreign_collection",
"localField": "field_in_current_collection",
"foreignField": "field_in_foreign_collection",
"as": "result"
}
}
from → The name of the collection we want to join.
localField → The field in the current collection.
foreignField → The field in the foreign collection that matches localField.
as → The output field where the joined data will be stored as an array.
mongodb+srv://sanjaysamantra:<password>@cluster0.geshq.mongodb.net/?
retryWrites=true&w=majority
mongodb+srv://sanjaysamantra1:berhampur@cluster0.ga81v5y.mongodb.net/
mongodb+srv://sanjaysamantra1:berhampur@cluster0.ga81v5y.mongodb.net/?
retryWrites=true&w=majority&appName=Cluster0
Mongoose
========
-Mongoose is a MongoDB object modeling tool.
-Mongoose is a JavaScript object-oriented programming library that creates a
connection between MongoDB and the Node.js.
-Provides features like: Data validation, Middleware and hooks, Schema
enforcement, Abstraction
https://mongoosejs.com/docs/guide.html
https://mongoosejs.com/docs/validation.html#built-in-validators
Mongoose Terminologies
======================
Schema:Mongoose schemas define the structure of the documents in a collection.
-Each schema maps to a MongoDB collection and defines the shape/structure of the
documents within that collection
new mongoose.Schema({eId: { type: Number,required:true,min:100,default:20 }});
Schema Types: String, Number, Boolean, Date, Array, ObjectId
Validation & Defaults: required: true , unique:true , default: Date.now
Constructing Documents:
-An instance of a model is called a document.
const emp = new EmployeeModel({ id:1,name:'sanjay });
await emp.save();
(or)
await emp.create({ id:1,name:'sanjay });
Querying:
-Finding documents is easy with Mongoose.
-Query Methods:
.find() → Retrieves all documents.
.findOne({ email: "john@example.com" }) → Retrieves a single document.
.findById(id) → Retrieves by ID
Ex: await UserModel.find({ add.city:'bangalore }).where('sa').gt(5000).exec();
Update a Document:
const updatedUser = await User.findByIdAndUpdate(id, { age: 35 }, { new:
true });
{ new: true } ensures the function returns the updated document.
Validating:
-Documents are casted and validated before they are saved. Mongoose first casts
values to the specified type and then validates them.
-Internally, Mongoose calls the document's validate() method before saving.
Built-in Validators : type, required, min, max, enum
Mongoose Virtuals:
-Virtuals allow to create computed fields without storing them in the database.
userSchema.virtual('fullName').get(function() {
return this.name + " (age: " + this.age + ")";
});
await session.commitTransaction();
session.endSession();
} catch (error) {
await session.abortTransaction();
session.endSession();
}
Mongoose Middleware
===================
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
// Create User Schema
const userSchema = new mongoose.Schema({
username: {
type: String,
required: [true, 'Username is required'],
unique: true,
trim: true,
lowercase: true, // Automatically converts input to lowercase
minlength: [3, 'Username must be at least 3 characters long'],
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
validate: {
validator: function (v) {
return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(v); // Simple email
regex validation
},
message: props => `${props.value} is not a valid email address!`
},
},
password: {
type: String,
required: [true, 'Password is required'],
minlength: [6, 'Password must be at least 6 characters long'],
},
createdAt: {
type: Date,
default: Date.now
}
});
// Generate a salt
const salt = await bcrypt.genSalt(10);
next();
});
module.exports = User;
Assignment
==========
-Using mongoose Create URL shorten application, with the below 2 APIS.
API-1
=====
http://localhost:5000/api/shorten (POST)
{
"originalUrl" : "https://www.youtube.com/results?
search_query=express+rate+limit"
}
returns a <code> as response
API-2
=====
GET : http://localhost:5000/e32nODMkC<CODE from API-1>
GraphQL
=======
-GraphQL is a query language for APIs.
-Alternative to REST, providing more flexibility by allowing clients to request
only the data they need.
-Uses a single endpoint for all requests.
Advantages of GraphQL
---------------------
Single Endpoint: Uses a single /graphql endpoint for all requests.
Flexible Queries: Clients can specify exactly what data they want.
Strongly Typed Schema: APIs are defined using a schema with types.
Real-time Updates: Supports subscriptions for real-time data updates.
Efficient Data Fetching: Reduces over-fetching and under-fetching of data.
REST GraphQL
============================================
1. Server Driven 1. Client Driven
2. Multiple endpoints 2. Single endpoint for all requests
3. Over-fetching data 3. Client requests exactly what is needed
4. No strict schema 4. Strongly typed schema
5. Requires WebSockets 5. Built-in subscriptions for real-time
updates
or polling separately
5. serve RURU UI
app.get('/', (req, res) => {
res.end(ruruHTML({ endPoint: '/graphql' }))
})
apollographql
=============
https://www.apollographql.com/docs
https://www.apollographql.com/docs/apollo-server
Redis
=====
-Redis Stands for 'Remote Dictionary Server'.
-fast, open source, in-memory, key-value data store.
-Redis speed makes it ideal for caching database queries, complex computations,
API calls, and session state.
-The stream data type enables high-rate data ingestion, messaging, event
sourcing, and notifications.
-Redis Cann't replace DB,it can only (set,get,delete)
How To Install Redis
====================
1. https://github.com/microsoftarchive/redis/releases
2. download Redis-x64-3.0.504.msi and install
3. add redis as path variable (Environment Variable)
C:\Program Files\Redis
4. check redis version (in command prompt)
redis-server -v
5. open command prompt & run the below command. (redis cli should open at
127.0.0.1:6379 )
redis-cli
Commands
========
Note : commands are not case sensitive (set/SET), Keys are case sensitive (get
name)
https://api.openweathermap.org/data/2.5/forecast/daily?
q=bangalore&mode=json&units=metric&cnt=5&appid=fbf712a5a83d7305c3cda4ca8fe7ef29
https://en.wikipedia.org/w/api.php?
action=query&format=json&prop=extracts&titles=India
https://api.github.com/users/google
https://dummyjson.com/products
Nodemailer
==========
-Nodemailer is a module for Node.js to send emails.
https://nodemailer.com/about/
https://nodemailer.com/usage/using-gmail/
Upload File
===========
1. express-fileupload
2. formidable
3. multer
Private Message
===============
socket.on("private message", ({ content, to }) => {
socket.to(to).emit("private message", {
content,
from: socket.id,
});
});
(OR)
https://socket.io/docs/v4/tutorial/introduction
ESLint
======
-ESLint is a static code analysis tool.
-Used for identifying problematic patterns found in JavaScript code.
-It makes the code more consistent, avoiding bugs.
-Pre-defined Rules:
no-debugger , no-unused-vars , no-dupe-keys , no-dupe-else-if , no-duplicate-
case, no-duplicate-imports
https://eslint.org/docs/latest/rules/
1. npm i eslint
2. npm init @eslint/config
(OR)
npx eslint --init
3. eslint . (linting will be running for a folder)
eslint abc.js (linting will be running for a file-abc.js)
eslint abc.js --fix (fixes the problems)
Swagger
=======
-It’s very important to write documentation for APIs so that whoever consumes
those APIs understand them, implement them, and play around with them.
-Swagger is a software tool used for designing, building, documenting, and using
RESTful APIs.
-create, update and share API definitions with consumers.
Steps:
1. npm init -y
2. npm install swagger-ui-express
3. add server.js & add Routes code
4. add the file swagger.json to define the operations.
http://rackerlabs.github.io/wadl2swagger/openstack/swagger/dbaas.json
5. add the file swagger.css to define custom css
6. Node server.js and try 'http://localhost:5000/api-docs/'
Sample Swagger.json
===================
{
"swagger": "2.0",
"info": {
"title": "User CRUD",
"version": "1"
},
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/users" : {
"get" : {},
"post" : {}
},
"/users/{id}" : {
"get" : {},
"patch" : {},
"delete" : {}
}
},
"definitions": {}
}
https://stackoverflow.com/questions/45518568/can-i-write-same-path-names-for-
different-methods-in-rest-api
Jasmine Terminologies
=====================
describe() Test suite (Group of testcases)
it() test case / spec
test() test case / spec
expect(actual).matcher(expected);
expect(app.add(2,3)).toBe(5);
Matchers
--------
toBe();
not.toBe();
toBeDefined();
not.toBeDefined();
toEqual();
toBeTruthy();
toBeFalsy();
toBeGreaterThan();
toBeLessThan();
toContain()
Stub
====
-stub is a function/object that replaces the actual behavior of a unit with a
fixed response.
-stub avoids calling the real implementation by overriding the original function
with our custom implementation.
-Allows to control the function behavior entirely.
Replaces the original function with:
A return value.
A fake implementation.
-ex: if we are testing a function that writes a value to the database, we should
write a stub that avoids the db interaction but returns a successful result.
Spy
===
-A spy is a tool used to observe and monitor the behavior of an existing
function.
-It allows to track if a function is called, how many times it’s called, with
what arguments, and other behaviors.
-it does not modify the original function unless explicitly configured to do so.
spyOn(someObj, 'func').and.returnValue(42);
spyOn(someObj, 'func').withArgs(2, 3).and.returnValue(5);
// app.js
const app = {
processData: (data) => {
console.log('Processing data:', data);
return data.length;
},
fetchData: () => {
const data = ['item1', 'item2', 'item3'];
return app.processData(data);
},
};
module.exports = app;
// app.spec.js
const app = require('./app');
describe('fetchData functionality', () => {
it('should call processData with the correct data', () => {
// Spy on processData, callThrough() ensures the original implementation
still runs
spyOn(app, 'processData').and.callThrough();
// Call fetchData
const result = app.fetchData();
// Assertions
expect(app.processData).toHaveBeenCalled(); // Verify processData was called
expect(app.processData).toHaveBeenCalledWith(['item1', 'item2',
'item3']); // Verify correct arguments
expect(result).toBe(3); // Verify the return value
});
});
Run Testcases
=============
mocha
mocha test/**/*.js
Code Coverage
=============
1. npm i nyc
Hooks
=====
-Mocha provides the hooks before(), after(), beforeEach(), and afterEach().
-These should be used to set up preconditions and clean up after tests are
executed.
Exclusive/Inclusive Test
========================
describe.only()
it.only()
describe.skip()
it.skip()
https://www.digitalocean.com/community/tutorials/test-a-node-restful-api-with-
mocha-and-chai
https://blog.logrocket.com/node-js-unit-testing-mocha-chai-sinon/
Basic Flow
==========
1. User logs in.
2. Server generates a JWT and sends that to user/client.
3. client receives the token and stores it somewhere in the browser
(session/local storage).
4. client sends the token in the Authorization header for protected
pages/routes/data.
5. Server checks the token, gets user information and sends the response to the
client.
https://blog.logicwind.com/jwt-refresh-token-implementation-in-node-js/
https://www.cloudzilla.ai/dev-education/how-to-build-authentication-api-with-
jwt-token-in-nodejs/
1. npm init -y
2. npm install express cors mongoose jsonwebtoken bcryptjs
PassportJS for Authentication
=============================
-Passport is middleware for Node.js to implement authentication and
authorization.
Render :
1. Register in Render and login
https://dashboard.render.com/register
2. new ---> web service
3. Connect to github Repo and Deploy
4. a live url should be generated after successful deployment
https://www.freecodecamp.org/news/how-to-deploy-nodejs-application-with-render/
https://devcenter.heroku.com/articles/deploying-nodejs
https://nodejs.org/en/learn/getting-started/profiling
Cinic.js
========
-help to diagnose performance issues, memory leaks, and event loop delays in
nodejs applications.
-provides automated analysis and recommendations for optimizing Node.js
applications
-Clinic.js consists of three main tools:
1. clinic doctor : Provides an overall diagnosis of the application
performance.
2. clinic bubbleprof : Helps visualize async operations and identify
bottlenecks.
3. clinic flame : Generates a flame graph to profile CPU usage and
identify slow functions.
https://www.simform.com/blog/nodejs-security/
https://anywhere.epam.com/en/blog/node-js-security-best-practices
https://www.aquasec.com/cloud-native-academy/application-security/node-js-
security/
Web-Hooks
=========
SOAP REST
======================================================
1.A XML based Message protocol 1.Architectural style
2.Uses WSDL For Communication 2.Uses JSON to send and receive data
3.Not easily readable 3.The result is easily readable
4.javascript cann't consume XML 4.Javascript can consume JSON
5.Performance - Not Great 5.Performs better than SOAP
CRON
=====
https://www.npmjs.com/package/node-cron
1. npm i node-cron
2.Add the below code
var cron = require('node-cron');
cron.schedule('* * * * *', () => { // * Every
console.log('running a task every minute');
});
1. second (optional)
2. minute
3. hour
4. day of month
5. month
6. day of week
* * * * * * Every Second
*/10 * * * * * Every 10 Second
* * * * * Every minute
*/2 * * * * Every 2 minute
0 * * * * Every Hour
0 */2 * * * Every alternate Hour
30 * * * * 30th minute of every hour
0 0 * * * every day 12 am
0 10 * * * every day 10 am
0 14 * * * every day 2 pm
0 10 * * 1 every monday 10 am
0 10 * * 1-5 Weekday 10:00 AM
0 10 */2 * * every alternate day 10 am
0 0 1 * * Every Month
0 0 1 1 * Every Year jan 1st
https://crontab.guru/examples.html
bull - https://www.npmjs.com/package/bull
The fastest, most reliable, Redis-based queue for Node.
Carefully written for rock solid stability and atomicity
PhonePe Integration
====================
https://developer.phonepe.com/v1/docs/api-integration/
https://developer.phonepe.com/v2/docs/technical-flow-diagram/
1. npm init -y
2. npm i express cors axios crypto
References:
===========
1. https://riptutorial.com/Download/node-js.pdf
2. https://nodejs.dev/en/learn/
3. https://www.tutorialsteacher.com/nodejs
4. https://www.javatpoint.com/nodejs-tutorial
5. https://www.guru99.com/node-js-tutorial.html
6. https://codeforgeek.com/nodejs/
7. https://www.geeksforgeeks.org/nodejs/
8. https://training-course-material.com/training/Nodejs
9. https://expressjs.com/en/advanced/best-practice-performance.html
---------------------------
express-rate-limit
md5 generator
joi validator
passportjs npm
rxjs
node profiler : https://nodejs.org/en/learn/getting-started/profiling
Monitoring Node.js applications with tools like PM2
clinic
Sample Projects
===============
https://github.com/itzabhinavarya/ShopingKaro
https://github.com/idurar/mern-admin
https://github.com/claykabongok/CRUD_REST_API_NODEJS_TYPESCRIPT
https://github.com/innextinit/foodOrdering?tab=readme-ov-file
https://github.com/omzi/madam-sauce/blob/stable/routes/auth.js
https://github.com/shoaib0657/foodmine/tree/main
---------------------------------------
Interview Questions
1- update() findOneAndUpdate()
2- drop & remove()
3- createIndex() & reIndex()
builds an index on a collection
rebuild all existing indexs on a collection
4- How to get system info on which mongoDB is running
db.hostInfo()
5- How to remove the current database ?
db.dropDatabse
6- How to rename a collection?
db.collection.renameCollection()
7 - findModify() findOneAndUpdate()
findModify - atomically modifies and return a single document
findOneAndUpdate - Find a single document and upd
https://medium.com/@ben.dev.io/node-js-for-real-time-communication-cf71f985f983
https://chatgpt.com/c/66dbe630-a978-800e-8a4b-1a3944ddbfc4