Beginner · Node.js and Express · topic 12 of 54 · 25 min
Node.js: JavaScript on the server
Explanation
JavaScript outside the browser
For many years JavaScript could only run inside a web browser. In 2009 Node.js changed that. Node.js is a runtime: a program that runs JavaScript code directly on a computer, with no browser and no web page.
Node.js uses V8, the same JavaScript engine that runs inside Google Chrome. An engine is the part that reads your code and turns it into instructions the computer understands. Node.js adds extra powers that a browser does not give you: reading and writing files, opening network connections, and starting a web server.
Install it and run your first file
- Open nodejs.org and download the LTS version. LTS means Long Term Support: the stable version that gets fixes for years. Pick it, not the newest "Current" one.
- Open a terminal and type node --version. If you see a number like v22.11.0, Node.js is installed.
- Make a file called hello.js with one line: console.log("Namaste from Node!").
- In the terminal, in the same folder, type node hello.js. The message prints in the terminal.
node --version
node hello.js
mkdir my-api
cd my-api
npm init -y
npm install expressnpm and package.json
npm is the Node Package Manager. A package is code that someone else wrote and shared, like Express for building web servers. npm init -y creates a file called package.json. This file is the ID card of your project: its name, the packages it needs (called dependencies) and short commands called scripts.
{
"name": "my-api",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node src/server.js",
"dev": "node --watch src/server.js"
},
"dependencies": {
"express": "^5.1.0"
}
}// file: src/gst.js
export function addGst(price) {
return Math.round(price * 1.18);
}
// file: src/server.js
import { addGst } from './gst.js';
console.log(addGst(1000)); // 1180The event loop: one waiter, many tables
Node.js runs your JavaScript on one main thread (one worker). Slow jobs like reading a database, a file or another website are called I/O (input and output). Node.js starts the I/O job and moves on to other requests. This is called non-blocking I/O. When the job finishes, the event loop picks up the result and runs the code that was waiting for it.
Promises and async/await
A Promise is an object that stands for a result that will arrive later, like a token number at a bank counter. An async function always returns a Promise. Inside it, the word await pauses only that function until the Promise is ready, while Node.js keeps serving everyone else. Promise.all starts several jobs at the same time and waits for all of them.
function findStudent(id) {
return new Promise((resolve) => setTimeout(() => resolve({ id, name: 'Meera' }), 100));
}
function findMarks(id) {
return new Promise((resolve) => setTimeout(() => resolve([78, 85, 91]), 100));
}
async function main() {
const [student, marks] = await Promise.all([findStudent(7), findMarks(7)]);
console.log(student.name, 'scored', marks);
}
main();Watch the lesson
Node.js: JavaScript on the server · 1/7
Today we take JavaScript out of the browser and run it on a server, with Node.js.
Prefer a video by a teacher? Find free videos on “node.js tutorial for beginners event loop async await” on YouTube ↗
In real life: A college results website on results day
On results day, thousands of students open the results page at the same moment. Each request needs a database lookup that takes, say, 50 milliseconds. A server that waited for each lookup before starting the next would build a long queue. A Node.js server starts every lookup, keeps accepting new students while the database works, and sends each result the moment it is ready. One small server can handle many students this way.
async function getResult(rollNo) {
const [student, marks] = await Promise.all([
db.findStudent(rollNo),
db.findMarks(rollNo),
]);
return { name: student.name, total: marks.reduce((a, b) => a + b, 0) };
}Practice (0/3 done)
getFee(name) pretends to be a slow database: it returns a Promise with the fee of a student. Write an async function totalFee(nameA, nameB) that gets both fees and returns their sum. Bonus: start both calls together with Promise.all.
A shop app shows a dashboard. Three fake database calls are given: findUser(id), findOrders(id) and findAlerts(id); each one is slow. Write an async function getDashboard(id) that loads all three AT THE SAME TIME with Promise.all and returns { name, orderCount, unread }, where unread is the number of alerts with read === false. If findUser gives null (no such user), return null. The fake database counts how many calls are running at the same moment, and the test checks that all three ran together.
Set up Node.js on your own computer. Install the LTS version, make a folder called my-api, create a project with npm and run a small file that prints your name and the total of three fees.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.