0% found this document useful (0 votes)
7 views

node_js_cheatsheet_withLinks_compressed

SDVBSD
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

node_js_cheatsheet_withLinks_compressed

SDVBSD
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

console.

log(systemInfo)

setTimeout(() => {

NodeJS
CHEAT SHEET

// Example paths

// Enable CORS for all routes


Connect with Alumni
Introduction to NodeJS

What is NodeJS?
It is a runtime environment that allows JavaScript for server-side programming,
enabling the execution of JavaScript code outside of a web browser.

Use case

Building high-performance Web servers and APIs


server -side applications

Real-time applications Application that needs


event-driven architecture

Architecture

THE NODE.JS SYSTEM

APPLICATION NODE.JS BINDINGS LIBUV


(NODE API) (ASYNCHRONOUS I/O)
JAVASCRIPT EVENT WORKER
QUEUE THREADS

BLOCKING FILE SYSTEM


OPERATIONS NETWORK

PROCESS
V8 EVENT
(JAVASCRIPT ENGINE) OS LOOP EXECUTE
OPERATION CALLBACK

02 NodeJS Cheatsheet
Working

Application Node.js Libuv


Bindings Event
(Node API) Queue
Task
Blocking Queue
JavaScript
ops
Event
Loop
Non-blocking ops
V8 Worker
I/O Polling Thread Pool
(epoll, kqueue, etc)

1.Start - Node.js application begins 5.Concurrency - Multiple events can be


its execution. processed concurrently, as the event loop
manages the execution of callback
2.Event Loop - Node.js operates on an functions.
event-driven, non-blocking I/O model. It is
constantly checking for events such as 6.I/O Operations - It is used for reading
incoming requests. from or writing to a file, making network
requests, or interacting with databases.
3.Event Triggered - When an event
(e.g., an HTTP request, or a file system 7.Non-Blocking - The non-blocking
operation) occurs, it triggers a callback nature of Node.js ensures that the
function. application can continue processing other
tasks while waiting for I/O operations to
4.Callback Execution - The callback complete, improving overall efficiency.
function associated with the event is
executed. Node.js uses asynchronous 8.Callback Queue - Completed callback
functions, allowing other tasks to continue functions are placed in a callback queue..
while waiting for non-blocking operations
to complete. 9.Event Loop (Again) - The event loop
checks for events and executes the
associated callbacks, pulling them from the
callback queue

03 NodeJS Cheatsheet
10.Repeat - The process repeats, allowing
Node.js to efficiently handle multiple
events simultaneously.

Incoming
Requests Event
Loop

Event Queue Worker


Thread Pool

Advantages and Disadvantages

Scalability Simple to Learn

Single Programming Large Community


Language Support

Freedom to Develop Node.js Web App Development


Cross Platform App Advantages Speed

Improved App
High Performance
Response Time

Cross-Platform
Caching
Development

Extensibility

04 NodeJS Cheatsheet
Asynchronous
Unstable API
Programming Model

NodeJS Disadvantages

Lack of Library Support

2 Installing and running NodeJS


Mac OS Windows

We can install Node.js on MacOS easily by We can install Node.js on Windows easily
using the installer from the official by using the installer from the official
Node.js website. Node.js website.

Linux (Ubuntu

There are various package managers available for each distribution. We can install
Node.js by using the Ubuntu official repository.

Command Comments

node Run node in your terminal

node --version To check node version if installed

node filename.js Executing the node code in file named filename.js

05 NodeJS Cheatsheet
03 Global Object in NodeJS

Global object

Can be accessed anywhere. Used where a feature is expected to be available everywhere.

For example, to have some code execute after 5 seconds we can use either
global.setTimeout or just setTimeout

Note: The global keyword is optional.

setTimeout(() => {
console.log('hello');
}, 5000);

//Two ways to access global


> console.log(global)
//or
> global

//Adding new property to global


> global.car = 'tesla'

You can also write global.console.log() to access global objects.

Note: It's important to note that while the global object provides accessibility across
modules, relying too heavily on global variables and functions can lead to code that is
harder to maintain and understand. Therefore, it's advisable to use globals judiciously
and consider alternative approaches for better code organization and readability.

06 NodeJS Cheatsheet
04 Process object in NodeJS

A process is the instance of a computer program that is being executed. Node has a
global process object NODE_ENV which can be used to determine the environment in
which the application is running

if (process.env.NODE_ENV === 'development'){


console.log('Do not deploy!! Do not deploy!!');
}

process.argv in NodeJS
process.argv in NodeJS process.memoryUsage in NodeJS

It is a property that holds an array of It is a method that can be used to return


command-line values provided when the information on the CPU demands of the
current process was initiated. current process

• First element→ absolute path


//using process.memoryUsage() will
• Next element→ file path that is running return an object in a format
like this:
• Finally→ command-line arguments were
{
provided when the process was initiated rss: 26247168,
heapTotal: 5767168,
heapUsed: 3573032,
external: 8772
// Command line values: node web.js }
testing several features

console.log(process.argv[2]);
// 'testing' will be printed

07 NodeJS Cheatsheet
Node.js and Asynchronous
05 Programming

Async VS Sync
Node.js leverages asynchronous
programming, employing a non-blocking Request 1 Request 1
event-driven architecture with callback
functions, to efficiently handle concurrent Request 2
Response 1
tasks like I/O operations, enhancing
Request 2
scalability and responsiveness. Response 1

Response 2 Response 2

Asynchronous Synchronous

06 Module system in NodeJS

1.Core module
Modules included within the environment to efficiently perform common tasks.

process.argv in NodeJS
console module os module

Exports a global console object os module can be used to get information


console.log() and other familiar methods about the computer and operating system
for debugging.. on which a program is running.

const os = require('os');

const systemInfo = {
'Home Directory': os.homedir(),
'Operating System': os.type(),
'Last Reboot': os.uptime()
};
// Printing systemInfo
console.log(systemInfo)

08 NodeJS Cheatsheet
Output:

{
'Home Directory': '/home/node',
'Operating System': 'Linux',
'Last Reboot': 1527.03
}

process.argv in NodeJS
util module path

Contains utility functions. Common uses The `path` module in Node.js provides
include runtime type checking with types utilities for working with file and directory
and turning callback functions into paths.
promises with the .promisify() method.
dir base

const util = require('util');


const fs = require('fs');
root name ext
// Using the .promisify() method to convert a
callback-based function to a Promise-based function
D:/ node.js/html/js \ app .js
const readFileAsync = util.promisify(fs.readFile);
/ node.js/html/js / app .js
// Example of reading a file using the converted
Promise-based function
Node.js path Module
readFileAsync('example.txt', 'utf8')
.then(data => {
console.log('File content:', data);
})
const path = require('path');
.catch(error => {
console.error('Error reading file:', error);
// Example paths
});
const dirPath = '/path/to/directory';
const filePath = 'file.txt';

Output: // Joining paths


const fullPath = path.join(dirPath, filePath);

// Normalizing the path


If file is present const normalizedPath = path.normalize(fullPath);

If file is not present console.log('Joined Path:', fullPath);


console.log('Normalized Path:', normalizedPath);

Output:

Joined Path: /path/to/directory/file.txt


Normalized Path: /path/to/directory/file.txt

09 NodeJS Cheatsheet
process.argv in NodeJS
fs

Read and write files on your file system.


const fs = require('fs');

// Example paths
open rename write read const inputFilePath = 'input.txt';
const outputFilePath = 'output.txt';

// Reading from a file


fs fs.readFile(inputFilePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
create append delete
// Writing to another file
fs.writeFile(outputFilePath, data, 'utf8', (err) => {
if (err) {
console.error('Error writing to file:', err);
return;
}

console.log('File content successfully


copied to', outputFilePath);
});
});

Output:
Output:

File content successfully copied to output.txt

2. require function
We can re-use existing code by using the Return value of
require(x)
Node built-in require() function. This function
function imports code from another require(x) = module.exports
module.
Module y module.exports Module x
object

const fs = require('fs');
fs.readFileSync('hello.txt');
// OR...
const { readFileSync } = require('fs');
readFileSync('hello.txt');

10 NodeJS Cheatsheet
3. Built-in modules 4. events module
Key built-in modules include: Used for EventEmitter, also has an .emit()
method which announces a named event
• fs → read and write files on your file that has occured.
system 1 2
listener 1 listener 2
• path → combine paths regardless of
which OS you're using invoke invoke

event 1
• process → information about the
get all the listeners for
currently running process, e.g. events/listener eventName and invoke
them sequentially with
object
key/value the args
process.argv for arguments passed in or
process.env for environment variables
emit
• http → make requests and create
HTTP servers eventName args

• https → work with secure HTTP servers


// Require in the 'events' core module
using SSL/TLS let events = require('events');

• events → work with the EventEmitter // Create an instance of the EventEmitter class
let myEmitter = new events.EventEmitter();
let version = (data) => {
• crypto → cryptography tools like console.log(`participant: ${data}.`);
};

encryption and hashing // Assign the version function as the listener


callback for 'new user' events
myEmitter.on('new user', version)

// Emit a 'new user' event


myEmitter.emit('new user', 'Doremon')
// 'Doremon'

11 NodeJS Cheatsheet
5. error module 6. buffer object
It doesnʼt have a specific error module. A Buffer is an object that represents a static
The callback function has an error passed amount of memory that canʼt be resized.
as a first parameter. If there is no error The Buffer class is within the global buffer
then that parameter is undefined. module, meaning it can be used without
the require() statement.

Data passed on Data

7. timers module 8. How to create modules


The global timers module contains We can create our own modules by
scheduling functions such as setTimeout(), exporting a function from a file and
setInterval(), and setImmediate(). These importing it in another module.
functions are put into a queue processed at
every iteration of the Node.js event loop. // In src/fileModule.js
function read(filename) { }
function write(filename, data) { }
module.exports = {
read,
write,
};
// In src/sayHello.js
const { write } = require('./fileModule.js')
write('hello.txt', 'Hello world!')

Some Node modules may instead use the


shorthand syntax to export functions.

// In src/fileModule.js
exports.read = function read(filename) { }
exports.write = function write(filename, data) { }

12 NodeJS Cheatsheet
9. ECMAScript modules
The imports above use a syntax known as
CommonJS (CJS) modules. Node treats // In src/fileModule.mjs
function read(filename) { }
JavaScript code as CommonJS modules by function write(filename, data) { }
export {
default. More recently, you may have seen read,
write,
the ECMAScript module (ESM) syntax. This };
// In src/sayHello.mjs
is the syntax that is used by TypeScript import { write } from './response.mjs';
write('hello.txt', 'Hello world!');

Extension: .mjs

07 Setting up the server with HTTP

HTTP messages can be protected using Transort Layer Security (TLS), a protocol
designed to facilitate secure data transmission via encryption.

1. .createServer() Method

• Create an HTTP server


const http = require('http');
• Takes a single argument in the form // Create instance of server
const server = http.createServer((req, res) => {
of a callback function res.end('Server is running!');
});

• Callback function has two primary // Start server listening on port 8080
server.listen(8080, () => {
const { address, port } = server.address();
arguments; the request (commonly console.log(`Server is listening on: http://${address}:${port}`);
});

written as req) and the response


(commonly written as res)

13 NodeJS Cheatsheet
2. Request Object 3. Response Object
• Contains information about the • Contains information about the
incoming HTTP request outgoing HTTP response
• Handle server requests such as routing • Contains various properties and
and data processing methods that can be used to configure
and send the response such as
.statusCode, .setHeader(), and.end()

4. url Module
const http = require('http');

const server = http.createServer((req, res) => {

// Set status and headers


Some Node modules
res.statusCode = 200; may instead use the
res.setHeader('Content-Type', 'application/json');
Used to break down URLs into their shorthand syntax to export functions.
constituent parts. // Send response
res.end('Hello World');
});
Parse URL
server.listen(8080)

http:/www.tutorialkart.com/index.php?type=page

Hostname Search

Pathname

/* Deconstructing a URL */

// Create an instance of the URL class


const url = new URL('https://www.example.com/p/a/t/h?query=string');

// Access parts of the URL as properties on the url instance


const host = url.hostname; // example.com
const pathname = url.pathname; // /p/a/t/h
const searchParams = url.searchParams; // {query: 'string'}

/* Constructing a URL */

// Create an instance of the URL class


const createdUrl = new URL('https://www.example.com');

// Assign values to the properties on the url instance


createdUrl.pathname = '/p/a/t/h';
createdUrl.search = '?query=string';

createUrl.toString(); // Creates https://www.example.com/p/a/t/h?query=string

14 NodeJS Cheatsheet
5. Query String 6. Request Body
Parameters
• Used in conjunction with GET requests • Data is commonly provided in the body
to submit information used in of a request
processing a request • The body is most commonly used in
• Provide filter criteria for some requested POST and PUT requests as they usually
data have information that needs to be
processed by the server

7. HTTP Headers 8. querystring Module


• Provide metadata that is used by • Used to decode/encode and parse
servers to process requests query string parameters into easily
usable data structures
• Operates on query string parameters,
requiring isolation of the query string
before use
• Methods of the module are .parse(),
.stringify() , .escape(), and .unescape()

URL Prameter Name Prameter Value

http://www.pronteff.com/page.html?parameter1=[@field:fieldname]&parameter2=[@field:fieldname2]

Query String Begin Equal Sign Query String Seperator

What are Query String Parameters & Methods in NodeJS

15 NodeJS Cheatsheet
9. HTTP and Databases 10. HTTP and External
APIs
• HTTP requests can be used to interact • Used to interact with other external
with databases to retrieve remote data APIs from within a server

Client Side Server Side


• A common way to request another
1.HTTP Request 2.Data Request server is through the .request() method
Browser Web Server Database
4.HTTP Response 3.Data Response on the http module

const options = {
hostname: 'example.com',
port: 8080,
path: '/projects',
method: 'GET',

11. HTTP Response headers: {

}
'Content-Type': 'application/json'

Status Codes }

// Make request to external API


const request = http.request(options, res => {
// Handle response here
});
• Indicate whether a specific HTTP
request has been completed
• Conveys information about what happened during the processing of the request

The server acknowledges


1XX Informational codes and is processing the request. const http = require('http');

// Creates server instance


const server = http.createServer((req, res) => {
try {
The server successfully recieved, // Do something here
2XX Success codes understood, and processed the } catch(error) {
requests. res.statusCode = 500; // Sets status code to indicate server error
return res.end(JSON.stringify(error.message));
}
The server recieived the request, });
but thereʼs a redirect to somewhere
3XX Redirection codes else (or, in rare cases, some // Starts server listening on specified port
server.listen(4001, () => {
additional action oter than a redirect
const { address, port } = server.address();
must be completed. console.log(`Server is listening on: http://${address}:${port}`);
});
The server couldnʼt find (or reach)
4XX Client error codes the page or website. This is an error
on the siteʼs side.

The client made a valid request, but


5XX Server error codes the server failded to complete the
request.

16 NodeJS Cheatsheet
08 Packages in NodeJS
A package is a collection of Node modules along with a package.json file describing
the package

1.npm command

Command Comments

Execute the current Node package defined by package.json;


npm start
defaults to node server.js

npm init Initialize a fresh package.json file

Initialize a fresh package.json file, accepting all default options


npm init -y
(equivalent to npm init --yes).

Install a package from the NPM registry at www.npmjs.com


npm install
(equivalent to npm i <package>).

Install a package as a development dependency (equivalent to


npm install -D
npm install --save-dev <package>).

npm install -g Install a package globally.

Update an already installed package


npm update <package>
(equivalent to npm up <package>).

npm uninstall Uninstall a package from your node_modules/ folder


<package> (equivalent to npm un <package>).

npm outdated Check for outdated package dependencies.

npm audit Check for security vulnerabilities in package dependencies.

Try to fix any security vulnerabilities by automatically


npm audit fix
updating vulnerable packages.

17 NodeJS Cheatsheet
2. package.json file 3. node_modules

It contains: • Next to your package.json file


• Name, version, description, and license • When you run npm install the packages
of the current package. listed as dependencies in your
• Scripts to automate tasks like starting, package.json are downloaded from the
testing, and installing the current NPM registry and put in the
package. node_modules folder. It contains not
• Lists of dependencies that are required just your direct dependencies, but also
to be installed by the current package the dependencies of those dependencies.
The entire dependency tree lives in
node_modules.

4. package-lock.json

• The package-lock.json file is


automatically created by NPM to track
the exact versions of packages that are
installed in your node_modules folder.

18 NodeJS Cheatsheet
09 Event emitter in NodeJS

Node.js provides a built-in module to


work with events listener

const EventEmitter = require('events');


const celebrity = new EventEmitter(); emits
celebrity.on('success', () => { listener listener
console.log('Congratulations! You are the best!');
});
celebrity.emit('success'); // logs success message EventEmitter
celebrity.emit('success'); // logs success message again
celebrity.emit('failure'); // logs nothing
listener listener
emits

Some examples include the currently


running Node process, a running HTTP listener

server, and web sockets. They all emit


events that can then be listened for using
a listener function like on().

const process = require('process');


process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});

19 NodeJS Cheatsheet
10 Concept of the backend in NodeJS

CRUD

Create Read Update Delete

CRUD
HTTP Method Example
Operation

Create POST POST /cards - Save a new card to the cards collection

Read GET GET /cards - Get the whole cards collection

Read GET GET /cards/:cardId - Get an individual card

Update PUT (or PATCH) PUT /cards/:cardId - Update an individual card

Delete DELETE DELETE /cards/:cardId - Delete an individual card

Delete DELETE DELETE /cards - Delete the entire collection of cards

20 NodeJS Cheatsheet
11 Express.js

Routers GET route


// In src/cards.router.js // Get a whole collection of JSON objects
const cardsRouter = express.Router(); app.get("/cards", (req, res) => {
cardsRouter.get("/", (req, res) => { return res.json(cards);
return res.json(cards); });
}); // Get a specific item in a collection by ID
cardsRouter.get("/:cardId", (req, res) => { app.get("/cards/:cardId", (req, res) => {
const cardId = req.params.cardId; const cardId = req.params.cardId;
return res.json(cards[cardId]); return res.json(cards[cardId]);
}); });
// In src/api.js
const cardsRouter = require('./cards.router');
const api = express.Router();
api.use('/cards', cardsRouter);

POST route
app.post("/cards", (req, res) => {
// Get body from the request
const card = req.body;
// Validate the body
if (!card.value || !card.suit) {
return res.status(400).json({
error: 'Missing required card property',
});
}
// Update your collection
cards.push(card);
// Send saved object in the response to verify
return res.json(card);
});

21 NodeJS Cheatsheet
12 Middlewares in Express

Middleware Stack

next() next()
Request 1 2 3 Response

Body Parsing Authentication Router

1. What are Middlewares 2. Custom Middlewares

• Functions that have access to the Functions that can be created to perform
request, response objects, and the specific tasks or validations in the
next function in the applicationʼs request-response cycle, adding customized
request-response cycle, allowing for processing to routes.
pre-processing, modification, or
termination of the request flow based
on specific conditions.
• Enhance the functionality of the server
by adding layers of processing between
the client and the final route handlers

22 NodeJS Cheatsheet
3. Third-Party
Middlewares
Third-party Middlewares in Node.js are
pre-built middleware functions provided by
external libraries, often used to add
common functionality (e.g., authentication,
logging) to an application with minimal
setup

13 Folder structure in NodeJS

Here's a commonly used and recommended structure for a basic Node.js application.

project-root/

├── node_modules/ // Installed npm packages (auto-generated)
├── public/ // Static files (e.g., HTML, CSS, client-side JavaScript)
├── src/ // Source code
│ ├── controllers/ // Route controllers
│ ├── models/ // Data models
│ ├── routes/ // Express route definitions
│ ├── services/ // Business logic and external services
│ ├── utils/ // Utility functions
│ └── app.js // Main application file

├── views/ // View templates (if using a templating engine like EJS)
├── .gitignore // Git ignore file
├── package.json // Project metadata and dependencies
├── package-lock.json // Dependency lock file (auto-generated)
├── README.md // Project documentation
└── .env // Environment variables configuration file

23 NodeJS Cheatsheet
14 Cross-origin resource sharing

Security feature implemented by web


browsers to control which web pages can const express = require('express');
const cors = require('cors');
make requests to a given resource from a const app = express();
different domain. // Enable CORS for all routes
app.use(cors());

// Your routes and other middleware can be defined here

const PORT = process.env.PORT || 3000;


app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

15 PM2 commands

• PM2 is a tool we use to create and manage Node.js clusters. It allows us to create
clusters of processes, manage those processes in production, and keep our
applications running forever.
• We can install the PM2 tool globally using npm install -g pm2

24 NodeJS Cheatsheet
HTTP Method Example

pm2 list List the status of all processes managed by PM2

pm2 start
Start server.js in cluster mode with 4 processes
server.js -i 4

pm2 start Start server.js in cluster mode with the maximum


server.js -i 0 number of processes.

pm2 logs Show logs from all processes.

pm2 logs --
Show older logs up to 200 lines long.
lines 200

Display a real-time dashboard in your terminal with


pm2 monit
statistics for all processes.

pm2 stop 0 Stop running process with ID 0.

pm2 restart 0 Restart process with ID 0.

Remove process with ID 0 from PM2's list of managed


pm2 delete 0
processes.

pm2 delete all Remove all processes from PM2's list.

Zero downtime reload of all processes managed by


pm2 reload all PM2. For updating and reloading server code already
running in production.

25 NodeJS Cheatsheet

You might also like