Node Js
Node Js
CHEAT SHEET
ADAM ODZIEMKOWSKI
V1.01
HEEELLLOOOOO!
I’m Andrei Neagoie, Founder and Lead Instructor of the Zero To Mastery Academy.
After working as a Senior Software Developer over the years, I now dedicate 100% of my time to
teaching others valuable software development skills, help them break into the tech industry, and
advance their careers.
In only a few years, over 600,000 students around the world have taken Zero To Mastery courses and
many of them are now working at top tier companies like Apple, Google, Amazon, Tesla, IBM,
Facebook, and Shopify, just to name a few.
This cheat sheet, created by our Node JS instructor (Adam Odziemkowski) provides you with the key
Node JS concepts that you need to know and remember.
If you want to not only learn node.js but also get the exact steps to build your own projects and get
hired as a backend or fullstack developer, then check out our Career Paths.
Happy Coding!
Andrei
P.S. I also recently wrote a book called Principles For Programmers. You can download the first five
chapters for free here.
Node JS Cheat Sheet: Zero To
Mastery
TABLE OF CONTENTS
Running Node.js
Node.js Global Object
Node.js Module System
The require Function
Built-in Modules
Creating Modules
ECMAScript Modules
Node.js Packages
NPM Commands
package.json
node_modules
package-lock.json
Node.js Event Emitter
Backend Concepts
Express.js
GET Routes
POST Routes
Routers
Node.js Folder Structure
Cross Origin Resource Sharing
PM2 Commands
Useful Links
Command Comments
node Run the Node REPL in your terminal
node —version Print your current Node version
node filename.js Execute the Node code in filename.js
REPL stands for Read Eval Print Loop. This is the list of steps that happen when you run the node com
For example, to have some code execute after 5 seconds we can use either
global.setTimeout or just setTimeout . The global keyword is optional.
// OR...
Built-in Modules
Some modules like fs are built in to Node. These modules contain Node-specific
features.
process - information about the currently running process, e.g. process.argv for
arguments passed in or process.env for environment variables
Creating Modules
We can create our own modules by exporting a function from a file and importing it in
another module.
module.exports = { read,
write,
};
// In src/sayHello.js
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) { }
ECMAScript Modules
The imports above use a syntax known as CommonJS (CJS) modules. Node treats
JavaScript code as CommonJS modules by default. More recently, you may have seen
the ECMAScript module (ESM) syntax. This is the syntax that is used by TypeScript.
// In src/sayHello.mjs
import { write } from './response.mjs'; write('hello.txt', 'Hello world!');
We tell Node to treat JavaScript code as an ECMAScript module by using the .mjs file
extension. Pick one approach and use it consistently throughout your Node project.
Node.js Packages
Node developers often publicly share packages, that other developers can use to help
solve common problems. A package is a collection of Node modules along with a
package.json file describing the package.
To work with Node packages we use NPM. NPM includes two things:
1. The NPM registry with a massive collection of Node packages for us to use.
We can search the NPM registry for packages atThe NPM tool will by default install packages from this
NPM Commands
Command Comments
Execute the current Node package defined by package.json. Defaults to
npm start
executing node server.js .
npm init Initialize a fresh package.json file
Initialize a fresh package.json file, accepting all default options. Equivalent
npm init -y
to npm init —yes
npm install Equivalent to npm i
npm install Install a package from the NPM registry at www.npmjs.com Equivalent to
<package> npm i <package>
npm install -D Install a package as a development dependency Equivalent to npm install
<package> —save-dev <package>
npm install -g
Install a package globally.
<package>
npm update
Update an already installed package Equivalent to npm up <package>
<package>
npm uninstall Uninstall a package from your node_modules/ folder Equivalent to npm un
<package> <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 updating vulnerable
npm audit fix
packages.
package.json
Most Node applications we create include a package.json file, which means our Node
applications are also Node packages.
2. Scripts to automate tasks like starting, testing, and installing the current package.
node_modules
This folder lives next to your package.json file.
When you run npm install the packages listed as dependencies in your package.json
are downloaded from the NPM registry and put in the node_modules folder.
It contains not just your direct dependencies, but also the dependencies of those
dependencies. The entire dependency tree lives in node_modules.
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. Share your package-
lock.json with other developers on your team to ensure that everyone is running the
exact same versions of every package in the dependency tree.
celebrity.emit('success'); // logs success message celebrity.emit('success'); // logs success message again celeb
Many features of Node are modelled with the EventEmitter class. Some examples
include the currently running Node process , a running HTTP server, and web sockets.
They all emit events that can then be listened for using a listener function like on() .
Backend Concepts
Client-server architecture
Your frontend is usually the client. Your backend is usually the server.
In a client-server architecture, clients get access to data (or "resources") from the
server. The client can then display and interact with this data.
The client and server communicate with each other using the HTTP protocol.
API
On the web, backend APIs are commonly defined by a list of URLs, corresponding
HTTP methods, and any queries and parameters.
CRUD
These are the basic operations that every API supports on collections of data. Your
API will usually save (or "persist") these collections of data in a database.
RESTful
RESTful APIs are those that follow certain constraints. These include:
Client-server architecture. Clients get access to resources from the server using
the HTTP protocol.
CRUD
HTTP method Example
Operation
Create POST POST /cards Save a new card to the cards collection
GET /cards Get the whole cards collection or... GET
Read GET
/cards/:cardId Get an individual card
PUT (or more
Update PUT /cards/:cardId Update an individual card
rarely PATCH)
DELETE /cards/:cardId Delete an individual card or more
Delete DELETE
rarely... DELETE /cards Delete the entire collection of cards
Express.js
GET Routes
POST Routes
Routers
// In src/cards.router.js
const cardsRouter = express.Router();
// In src/api.js
const cardsRouter = require('./cards.router'); const api = express.Router(); api.use('/cards', cardsRouter);
# top level router connecting all the above routes # any long running servi
# e.g. connecting to a MongoDB database # all Express middleware and router
# the top level Node HTTP server
This is just a reference. In the real world, every project will have differences in the
requirements and the ideal project structure.
Browsers follow the Same Origin Policy (SOP), which prevents requests being made
across different origins. This is designed to stop malicious servers from stealing
information that doesn't belong to them.
Cross Origin Resource Sharing (CORS) allows us to allow or whitelist other origins
that we trust, so that we can make requests to servers that don't belong to us. For
example, with CORS set up properly, https://www.mydomain.com could make a
POST request to https://www.yourdomain.com
Command Comments
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 number of processes to take full
server.js -i 0 advantage of your CPU.
pm2 logs Show logs from all processes.
pm2 logs —
Show older logs up to 200 lines long.
lines 200
pm2 monit Display a real-time dashboard in your terminal with statistics for all processes.
pm2 stop 0 Stop running process with ID 0.
pm2 restart 0 Restart process with ID 0.
pm2 delete 0 Remove process with ID 0 from PM2's list of managed processes.
pm2 delete
Remove all processes from PM2's list.
all
pm2 reload Zero downtime reload of all processes managed by PM2. For updating and
all reloading server code already running in production.