Episode 3 — NodeJS MongoDB Backend Architecture / 3.1 — Starting with NodeJS

3.1 — Quick Revision: Starting with Node.js

A compact cheat sheet covering Node.js fundamentals, setup, globals, npm, and package.json.


< Interview Questions | README


How to use this material

  1. Read through once after completing all subtopics (3.1.a through 3.1.e).
  2. Cover the right column of each table and try to recall the answer from the left column.
  3. Print this page for quick reference before interviews or exams.
  4. Flag anything you cannot recall and revisit that specific lesson file.

Core Vocabulary

TermDefinition
Node.jsJavaScript runtime built on V8 + libuv + Node APIs — runs JS outside the browser
V8Google's C++ JavaScript engine — compiles JS to machine code via JIT
libuvC library providing the event loop, thread pool (4 default), and async I/O
Event loopSingle-threaded loop that delegates I/O and processes callbacks from queues
Non-blocking I/OI/O operations are delegated and do not block code execution
npmNode Package Manager — registry (2M+ packages) + CLI tool + website
npxRun packages without global installation — always uses latest version
SemVerMAJOR.MINOR.PATCH versioning — ^ allows minor+patch, ~ allows patch only
LTSLong-Term Support — even-numbered Node.js versions (18, 20, 22)
REPLRead-Eval-Print-Loop — interactive Node.js shell (node with no args)
CommonJSrequire() / module.exports — Node.js original module system
ES Modulesimport / export — the modern JavaScript standard

Node.js vs Browser JavaScript

FeatureBrowserNode.js
Global objectwindowglobal
Universal globalglobalThisglobalThis
DOMdocument, window.documentNot available
File systemNot availablefs module
HTTP serverNot availablehttp module
Module systemES ModulesCommonJS + ES Modules
Process controlNot availableprocess object
__dirnameNot availableAvailable (CJS only)

npm Commands Cheat Sheet

CommandWhat It Does
npm init -yCreate package.json with defaults
npm install / npm iInstall all dependencies from package.json
npm i expressInstall package (adds to dependencies)
npm i nodemon -DInstall as devDependency
npm i -g typescriptInstall globally
npm i express -EInstall exact version (no ^ or ~)
npm uninstall expressRemove a package
npm updateUpdate packages within SemVer range
npm outdatedShow which packages have newer versions
npm ls --depth=0List top-level installed packages
npm auditCheck for security vulnerabilities
npm audit fixAuto-fix vulnerabilities
npm ciClean install from lock file (for CI/CD)
npm run <script>Run a custom script from package.json
npm startRun the "start" script (no "run" needed)
npm test / npm tRun the "test" script (no "run" needed)
npx <package>Run a package without installing globally

nvm Commands Cheat Sheet

CommandWhat It Does
nvm install --ltsInstall latest LTS version
nvm install 20Install latest Node.js 20.x
nvm use 20Switch to Node.js 20.x
nvm lsList installed versions
nvm alias default 20Set default for new terminals
nvm currentShow active version
nvm uninstall 16Remove a version
nvm useUse version from .nvmrc

node Command Cheat Sheet

CommandWhat It Does
node app.jsRun a JavaScript file
nodeStart the REPL
node -vPrint Node.js version
node -e "code"Execute inline code
node -p "expr"Evaluate and print result
node --check app.jsSyntax check without running
node --watch app.jsAuto-restart on file changes (Node 18+)
node --env-file=.env app.jsLoad .env file (Node 20.6+)

package.json Key Fields

FieldPurposeExample
namePackage name (lowercase, no spaces)"my-api"
versionSemVer version"1.0.0"
descriptionOne-line summary"REST API for my app"
mainEntry point for require()"src/index.js"
typeModule system"module" or "commonjs"
scriptsCustom npm commands{ "start": "node server.js" }
dependenciesRuntime packages{ "express": "^4.18.2" }
devDependenciesDevelopment-only packages{ "jest": "^29.7.0" }
peerDependenciesConsumer must provide{ "express": "^4.0.0" }
enginesRequired Node/npm version{ "node": ">=20" }
privatePrevent accidental publishingtrue
exportsModern entry point map{ ".": { "import": "..." } }

Node.js Global Objects and Variables

GlobalWhat It Is
processCurrent process info — argv, env, cwd(), exit(), pid
consoleOutput methods — log, error, warn, table, time
__dirnameAbsolute path to the directory of the current file (CJS only)
__filenameAbsolute path to the current file (CJS only)
globalThe global namespace object
globalThisUniversal global (works in browser and Node.js)
BufferHandle binary data
setTimeoutSchedule a callback after a delay
setIntervalSchedule a recurring callback
setImmediateSchedule a callback in the check phase
require()Import a module (CJS only)
moduleReference to the current module (CJS only)

Dependency Types Quick Reference

TypeIn production?Install commandExample packages
dependenciesYesnpm i expressexpress, mongoose, bcrypt, cors
devDependenciesNonpm i jest -Djest, eslint, nodemon, prettier
peerDependenciesMust existConsumer installsexpress (for plugins)

SemVer Range Symbols

SymbolMeaning^4.18.2 allows
^ (caret)Minor + patch updates>=4.18.2 <5.0.0
~ (tilde)Patch updates only>=4.18.2 <4.19.0
(none)Exact versionOnly 4.18.2
*Any versionLatest

CommonJS vs ES Modules

FeatureCommonJSES Modules
Importrequire('pkg')import pkg from 'pkg'
Exportmodule.exports = ...export default ...
LoadingSynchronousAsynchronous
Top-level awaitNoYes
Tree-shakingNoYes
__dirnameAvailableUse import.meta.url
File extension.js or .cjs.js (with "type":"module") or .mjs
Default in Node.jsYesOpt-in via "type":"module"

Event Loop Phases (Simplified)

┌─► timers         ← setTimeout, setInterval callbacks
│   pending        ← deferred I/O callbacks
│   poll           ← retrieve + execute I/O callbacks
│   check          ← setImmediate callbacks
│   close          ← socket.on('close') callbacks
└───────────────── (repeat)

Microtasks (process.nextTick, Promises) run BETWEEN every phase.

Execution order:

  1. Synchronous code
  2. process.nextTick callbacks
  3. Resolved Promise callbacks (.then)
  4. setTimeout / setImmediate callbacks

Master Workflow: New Project Setup

# 1. Create and enter project directory
mkdir my-project && cd my-project

# 2. Set Node.js version
echo "20" > .nvmrc && nvm use

# 3. Initialize project
npm init -y

# 4. Set up .gitignore
echo "node_modules/\n.env\n.DS_Store\ndist/\ncoverage/" > .gitignore

# 5. Create entry point
touch index.js

# 6. Install dependencies
npm i express dotenv cors
npm i -D nodemon jest eslint

# 7. Initialize git
git init && git add -A && git commit -m "Initial commit"

# 8. Run
npm start        # production
npm run dev      # development

Files to Commit vs Ignore

CommitIgnore (.gitignore)
package.jsonnode_modules/
package-lock.json.env
.nvmrc.DS_Store
.gitignoredist/
Source code (src/)coverage/

<- Back to 3.1 — Starting with Node.js (README)