๐Ÿ–ฅ๏ธ
Arc D โ€” Server-Side Code. Node.js runs on your machine or server, not in the browser. The code examples below are read-only and show real terminal output. There is no browser preview โ€” run these yourself with node filename.js after installing Node.js from nodejs.org.

1. What is Node.js

JavaScript was designed for browsers โ€” it runs inside Chrome, Firefox, or Safari and can manipulate web pages. But for most of its life, JavaScript couldn't do anything outside a browser tab. You couldn't read files, connect to a database, or listen for HTTP requests.

Node.js changed that in 2009. It takes Chrome's V8 JavaScript engine โ€” the same one that compiles your browser's JavaScript into fast machine code โ€” and embeds it in a standalone runtime you can install on any computer or server.

How Node.js Works
Your JS Code
index.js
โ†’
V8 Engine
Compiles to machine code
โ†’
libuv
Non-blocking I/O, event loop
โ†’
OS / Network / Files
Real system operations

Node.js is event-driven and uses non-blocking I/O. This means when Node asks the OS to read a file or make a database query, it doesn't sit idle waiting. It registers a callback and moves on to handle other work. When the file is ready, it fires the callback. This makes Node extremely efficient at handling thousands of simultaneous connections โ€” perfect for API servers.

๐Ÿ›’
UrbanCart Example
Why UrbanCart's backend runs on Node.js

UrbanCart's checkout page triggers many simultaneous operations: check inventory, validate payment, send confirmation email, update order database. With Node's non-blocking I/O, all of these can be kicked off concurrently without blocking each other. The server stays responsive to the next customer's request while waiting for the database to reply.

Key terms: Event-driven โ€” code runs in response to events (HTTP request, file read complete, timer fired). Non-blocking I/O โ€” Node doesn't freeze while waiting for slow operations. Single-threaded event loop โ€” one thread handles all connections through callbacks and async operations.

2. Why Node.js

Node.js has become one of the most popular server-side runtimes in the world. Here's why teams choose it:

๐Ÿ”

One Language

JavaScript on both frontend and backend. UrbanCart's React components and its API server share the same language, patterns, and even utility functions.

๐Ÿ“ฆ

NPM Ecosystem

Over 2 million packages on npm. Need JWT authentication, email sending, image processing, or PDF generation? There's a battle-tested package for it.

โšก

Great for APIs

Node's non-blocking model excels at I/O-heavy workloads โ€” reading from databases, calling external APIs, serving JSON. Exactly what a REST API does.

Where Node.js shines vs where it doesn't: Node is excellent for API servers, real-time apps (chat, notifications), and streaming. It is not ideal for CPU-intensive tasks like video transcoding or machine learning inference โ€” those block the event loop. For those, use dedicated workers or different runtimes.

3. Hello World in Node.js

Once you have Node.js installed (node --version to verify), you can run any .js file directly from the terminal.

hello.js Hello World script
Terminal output โ€” run with: node hello.js
$ node hello.js Hello from Node.js! Node version: v20.11.0 Platform: linux Current time: 2026-04-18T09:23:14.502Z

That's it. No build step, no bundler, no browser. Just node filename.js and your code runs. console.log works exactly the same as in the browser โ€” it just prints to your terminal instead.

4. npm & package.json

npm stands for Node Package Manager. It ships with Node.js and serves two purposes: installing packages from the npm registry, and managing your project's configuration through package.json.

Initialising a Project

Run npm init (or npm init -y to skip the questions) in a new folder. It creates package.json:

package.json UrbanCart backend project
๐Ÿ“Œ

dependencies

Packages your app needs in production โ€” Express, dotenv, cors. Installed with npm install package-name.

๐Ÿ”ง

devDependencies

Packages only needed during development โ€” nodemon (auto-restart), jest (testing). Installed with npm install -D package-name.

node_modules: When you run npm install, npm downloads all dependencies into a node_modules/ folder. Never commit this folder to git โ€” add it to .gitignore. Anyone who clones your repo runs npm install to restore it from package.json.

5. Running Scripts

The "scripts" field in package.json lets you define shortcut commands. Instead of remembering long commands, you run npm run scriptname.

terminal Common npm commands
Terminal โ€” starting the UrbanCart dev server
$ npm run dev > urbancart-backend@1.0.0 dev > nodemon index.js [nodemon] 3.0.1 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,cjs,json [nodemon] starting `node index.js` UrbanCart API listening on port 3000

The start script (npm start) is special โ€” it doesn't need run. Same for npm test. All other custom scripts need npm run scriptname.

Reading Command-Line Arguments with process.argv

Node passes command-line arguments via process.argv. The first two elements are always the node binary path and the script path โ€” your actual arguments start at index 2.

greet.js Using process.argv
Terminal output
$ node greet.js Alice Hello, Alice! Welcome to UrbanCart. All args: [ 'Alice' ] $ node greet.js Hello, stranger! Welcome to UrbanCart. All args: [] $ node greet.js Alice Bob Hello, Alice! Welcome to UrbanCart. All args: [ 'Alice', 'Bob' ]

6. CommonJS vs ES Modules

Node.js has two module systems. Understanding both is essential because you'll encounter them in different codebases and tutorials.

๐Ÿ“ฆ

CommonJS (CJS) โ€” the original

Uses require() to import and module.exports to export. Files use the .js or .cjs extension. This is the default in Node.js and still used by most packages.

๐Ÿ”ต

ES Modules (ESM) โ€” the standard

Uses import / export โ€” the same syntax as browser JavaScript and React. Files use .mjs or .js with "type": "module" in package.json.

products.js (CommonJS) require / module.exports
products.mjs (ES Modules) import / export
Which to use? For new projects with Node 18+, prefer ES Modules โ€” it's the standard and matches your React code. For existing projects or when a tutorial uses require(), stick with CommonJS. You cannot mix them in the same file without a workaround.

7. Global Objects

Node.js provides several global objects available in every file without importing anything. These replace browser globals like window and document.

globals.js Node.js global objects
Terminal output
$ PORT=4000 NODE_ENV=production node globals.js Port: 4000 Environment: production Script args: [] This file lives in: /home/user/urbancart-backend This file is: /home/user/urbancart-backend/globals.js UrbanCart ERROR: DATABASE_URL is not set.
process.env best practice: Never hard-code secrets (API keys, database passwords) in your source code. Store them in a .env file, add .env to .gitignore, and use the dotenv package to load them into process.env at startup. Example: require('dotenv').config() at the top of your entry file.

8. Reading & Writing JSON with fs

Node's built-in fs (file system) module lets you read and write files. For JSON data โ€” like a product catalogue stored on disk โ€” fs.readFileSync and fs.writeFileSync are the simplest approach.

products.json UrbanCart product data file
read-products.js Read and parse JSON from disk
Terminal โ€” node read-products.js
$ node read-products.js Loaded 6 products. First product: { id: 1, name: 'Wireless Headphones', price: 49.99, category: 'gadgets', inStock: true } All names: [ 'Wireless Headphones', 'USB-C Hub', 'Laptop Stand', 'Mechanical Keyboard', 'Monitor Light Bar', 'Webcam HD 1080p' ]

9. UrbanCart Filter Script

Let's put it all together. This script loads products.json, filters for in-stock gadgets under a price threshold (passed via command-line argument), and writes the results to a new file.

โš™๏ธ
UrbanCart Domain Script
Filter gadgets by price and write results to disk

UrbanCart's operations team runs nightly scripts to generate filtered product feeds for promotional emails. This script accepts a max price argument and writes matching in-stock gadgets to deals.json.

filter-gadgets.js Full UrbanCart domain script
Terminal โ€” node filter-gadgets.js 60
$ node filter-gadgets.js 60 Filtering gadgets priced under $60... Loaded 6 total products. Found 2 matching deals: - Wireless Headphones ($49.99) - USB-C Hub ($29.99) Results saved to: /home/user/urbancart-backend/deals.json
deals.json โ€” written to disk
[ { "id": 1, "name": "Wireless Headphones", "price": 49.99, "category": "gadgets", "inStock": true }, { "id": 2, "name": "USB-C Hub", "price": 29.99, "category": "gadgets", "inStock": true } ]
Try it yourself: After installing Node.js, create a folder with products.json and filter-gadgets.js from the examples above, then run node filter-gadgets.js 40 to filter gadgets under $40, or node filter-gadgets.js 100 to get all in-stock gadgets.

10. Quick Reference

A summary of the key Node.js concepts covered in this lesson.

reference.js Node.js cheat sheet

Quiz

Question 1 of 5
What JavaScript engine does Node.js use?
Question 2 of 5
What does require() do in Node.js?
Question 3 of 5
What is process.env used for in Node.js?
Question 4 of 5
What command runs a Node.js file called server.js?
Question 5 of 5
What is npm?
0
/ 5
Great job!

You completed the Node.js quiz.

Next Lesson

Express Basics โ†’
Next: build your first web server with Express.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You just brought JavaScript to the server.
Now build a full-stack career that runs anywhere.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’