15 min read
What is Node.js and what is it used for
In one sentence: Node.js is a program that runs JavaScript outside the browser, on your computer or on a server, and gives it what a web page doesn't have: reading files, using the network and talking to the system. It comes with npm, which installs code other people have written.
What you will learn
- Explain what Node.js is, what it adds to the browser's JavaScript and what it lacks.
- Run JavaScript in the REPL and in a file, and read a file from the disk with a Node module.
- Create a project with npm and explain what package.json, node_modules and the lockfile are for.
- Install a package with an exact version, and explain why the project waits 7 days and doesn't run scripts when installing.
Before you start, read: phase-1/05-processes-and-signals.md
The problem
Section titled “The problem”In Phase 2, the nginx of Ana and Luis’s shop answered /api/orders with a response written by hand in its configuration. Always the same one, whatever you asked for. A real shop needs a program that reads the order, checks the products, works out the total and answers: a BackendThe part of a website or app you don't see. It's the programs that, on servers, receive requests, store the data and decide what to answer.Go to definition, and someone has to write it.
In which language? One is already in every browser: JavaScriptThe programming language of web pages, which, with Node.js, is also used outside the browser to write servers. A JavaScript program is text with instructions that run one after another.Go to definition. But JavaScript was born to live inside a web page, and it’s locked in there on purpose. A page can’t read the files on your disk or sit listening on a PortA number, from 0 to 65535, that says which program on a computer a connection is for. The computer has an address; each listening program has its port.Go to definition. And luckily so: if it could, any website could steal your documents.
A server needs exactly what the browser forbids. Node.js takes JavaScript out of the browser and lets it work with your computer.
The analogy
Section titled “The analogy”The analogy
Think of a car engine. All it knows is how to turn, and what you get depends on where you mount it. In a car it moves the wheels, and you have a steering wheel and headlights. Mount the same engine in a motorboat and it moves a propeller: there are no wheels or headlights, but there’s a rudder.
The engine is V8, the program inside Chrome that runs JavaScript. The car is the browser, which gives it the web page to work with. The motorboat is Node.js: the same engine, mounted with other parts, the ones a server needs.
Where the analogy breaks down
- An engine doesn’t know where it has been mounted, and neither does your code: it doesn’t find out it’s in Node until it uses a part that doesn’t exist there, like the web page. Then it fails.
- Not every car has this engine: Firefox and Safari run JavaScript with other ones. The language is the same in all of them.
- Node isn’t just V8 with parts bolted on: it has its own way of waiting for the disk and the network without stopping, the most important thing in a server (lesson 9).
How it really works
Section titled “How it really works”JavaScript needs a program to run it
Section titled “JavaScript needs a program to run it”JavaScript is a programming language: text with instructions that the computer doesn’t understand as it is. It needs a program that translates it into processor instructions and runs it. In Chrome, that program is V8.
In 2009, Ryan Dahl took V8, pulled it out of the browser and put it in a program you start from the terminal: Node.js. You give it a JavaScript file and it runs it:
- Your filehello.js
node hello.js
- Node.jsthe program you start
hands it the code
- V8translates and runs it
asks for what it needs
- The operating systemthe terminal, the disk, the network
V8 plus what Node puts around it make up a RuntimeThe program that runs a language’s code and gives it access to what lies outside it, such as the screen, the files or the network. Node.js is a JavaScript runtime, and the browser is another.Go to definition: the program that runs a language and gives it access to what’s outside. The browser is one for web pages, and Node.js is one for programs on a computer or a server.
What Node.js adds and what it lacks
Section titled “What Node.js adds and what it lacks”The language is the same in both places: 2 + 3 gives 5 in Chrome and in Node. What changes is what’s around it:
| In the browser | In Node.js | |
|---|---|---|
The web page (document, window) |
Yes | No: there’s no page |
| Reading and writing files on the disk | No | Yes |
| Listening on a port, being a server | No | Yes |
| Environment variables, the process itself | No | Yes, in process |
Where console.log writes |
The DevTools console | The terminal |
A running Node program is a ProcessA running program. When you start a server, the operating system creates a process that stays alive waiting for requests.Go to definition, like the ones in lesson 5 of Phase 1: it has its PID and you stop it with Ctrl + C. From the code, what it knows about itself is in process: process.version is its Node version, and process.env, its environment variables.
The REPL: JavaScript line by line
Section titled “The REPL: JavaScript line by line”If you type node and nothing else, Node lets you write JavaScript line by line: it reads each line, runs it, shows you the result and waits again. That’s why it’s called the REPLREPL stands for Read-Eval-Print Loop.A way of working with a language in which you type a line of code, it runs and you see the result right away, without creating any file. In Node.js, you open it by typing node, with nothing else, in the terminal.Go to definition: read, evaluate, print, and loop back to the start.
It’s for trying out single things. When you leave with .exit, Node remembers the lines in a history, like the shell (↑), but there’s no program left that you can run again: that goes in a file.
A program is a .js file
Section titled “A program is a .js file”The hello.js you wrote in the introduction is already a program: a text file with JavaScript. node hello.js runs it from top to bottom and finishes: the process ends and the prompt comes back. A server, on the other hand, stays running, waiting for requests (lesson 4).
Modules: code in pieces
Section titled “Modules: code in pieces”The second program does something a web page can’t: read a file from the disk. It reads this one, with the shop’s products in JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition:
[ { "id": 1, "name": "T-shirt", "price": 20 }, { "id": 2, "name": "Mug", "price": 8.5 }, { "id": 3, "name": "Hoodie", "price": 35 }]And this is the program:
// Reads a file from the disk, something a web page can't do and Node.js can.import { readFile } from 'node:fs/promises';
const text = await readFile('products.json', 'utf8');const products = JSON.parse(text);
console.log(`The shop has ${products.length} products:`);for (const product of products) { console.log(`- ${product.name}: ${product.price} €`);}Piece by piece:
import { readFile } from 'node:fs/promises'brings in a piece from somewhere else: the FunctionA named piece of code that takes some data, does something with it and returns a result. It’s written once and used as many times as needed.Go to definitionreadFile. It comes fromfs(file system), and thenode:prefix says it’s Node’s own, built in.const text = await readFile('products.json', 'utf8')reads the file as text ('utf8'says how its letters are stored, accents and€included) and keeps it under a name,text.awaitwaits for the disk to answer (lesson 2).JSON.parse(text)turns that text into data the program can go through: a list of products.products.lengthsays how many it has.for (const product of products) { … }repeats what’s between the braces once for each product. Inside,product.nameandproduct.priceare its data, put into the text with${…}, as inhello.js.
Each code file is a ModuleA code file that offers some of its pieces to other files, which bring them in with import. This way a program is split across several files and can use the pieces that come with Node.js or with a package.Go to definition: it can offer pieces to others, which bring them in with import. The pieces come from Node (node:fs/promises), from other files of yours (lesson 3) or from code written by other people, with npm.
TypeScript too
Section titled “TypeScript too”Node 26 also runs .ts files, written in TypeScriptA language that is JavaScript with types: annotations that say what kind of data goes in each place, such as a number or a piece of text. The editor and the TypeScript checker warn about errors before the program runs, and Node.js runs it by erasing the types.Go to definition: JavaScript with notes about the type of each piece of data, which Node erases before running it. What you gain with them is in lesson 3.
npm: other people’s code
Section titled “npm: other people’s code”Node comes with npmThe package manager of Node.js, which comes installed with it. It’s both a command, which downloads packages into your project, and a public catalog on the internet where anyone can publish them. Although it’s often read as “Node Package Manager,” officially it isn’t an acronym.Go to definition, its Package managerA program that installs, updates and removes other programs from a catalog, and also brings the ones each of them needs to work. On Ubuntu it’s apt, on a Mac, Homebrew, and for Node.js code, npm. Some catalogs are looked after by a team, like Ubuntu’s; in others, like npm, anyone can publish.Go to definition (it’s usually read as Node Package Manager, although officially it isn’t an acronym). It’s two things:
- A catalog on the internet, the npm registry, with millions of Package (of code)Ready-to-use code that someone publishes with a name and a version number, so others can install it in their projects instead of writing it. In Node.js, packages are installed with npm and kept in the node_modules folder.Go to definition: code someone has published with a name and a version for others to use.
- A command,
npm, that downloads them into your project and notes down which ones you use.
There’s an important difference from apt, the one in lesson 6 of Phase 1: its catalog is prepared and signed by Ubuntu. On npm, anyone can publish a package, and nobody reviews it first. That’s its strength and its risk.
package.json: the project’s ID card
Section titled “package.json: the project’s ID card”An npm project is a folder with a package.json file. npm init -y creates one. This is the one in this lesson’s folder:
{ "name": "shop-api", "version": "1.0.0", "private": true, "type": "module", "engines": { "node": ">=24" }, "scripts": { "test": "node --test" }}Piece by piece:
nameandversion: the project’s name and its version."private": true: npm refuses to publish it, even if someone typesnpm publishby mistake."type": "module": the.jsfiles in this folder useimport. With"commonjs", Node expects the old system,require, the one in old tutorials.engines: which Node versions it works with. Here, 24 and later.scripts: named commands.npm testrunsnode --test, which runs the tests in each step’stest/folder (lesson 4).
node_modules and the lockfile
Section titled “node_modules and the lockfile”When you install a package, npm does three things:
- It downloads it into the
node_modulesfolder, along with the packages it needs. - It notes it down in
package.json, underdependencies, with the version you want. - It writes in
package-lock.json, the lockfile, the exact version of everything it has installed, where it came from and its HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, the file’s fingerprint.
Directoryshop-api/
Directorynode_modules/ what npm downloads: not saved in Git
Directorypicocolors/
- …
- .npmrc
- hello.js
- package-lock.json the lockfile: the exact versions
- package.json the project’s ID card
- products.json
- read-products.js
Thanks to the lockfile, your project installs the same way everywhere: npm install, with no package name, downloads exactly what it says, with its hash checked. That’s why package.json and the lockfile are saved in Git, and node_modules goes in .gitignore (you saw it in “Environment variables”): it’s created again with one command.
Versions and the ^
Section titled “Versions and the ^”In 1.1.1, the first number changes when something stops working as before, the second when something is added and the third when a bug is fixed. Without any configuration, npm writes "^1.1.1": “1.1.1 or any later one that starts with 1.” The lockfile holds back the jump, but an npm update or a deleted lockfile installs the latest 1.x, maybe published an hour ago.
The .npmrc: three lines against the 2025 attacks
Section titled “The .npmrc: three lines against the 2025 attacks”In 2025, npm suffered several serious attacks. Two of them:
- September: chalk and debug. An email impersonating npm support led the maintainer of 18 packages, chalk and debug among them, to type his password and his verification code into a fake website. The attackers published versions that redirected cryptocurrency payments, in packages with more than 2 billion downloads a week between them. Most were pulled within a few hours (Aikido).
- September and November: Shai-Hulud. A worm: code that ran when a package was installed, stole the npm, GitHub and cloud keys it found on the computer and, with the npm one, published infected versions of its victim’s packages. It infected more than 500 in September and came back in November (CISA).
This is the project’s .npmrc, npm’s configuration for this folder:
# Only installs versions at least 7 days old: versions with malicious code are usually found# and pulled before then. And it doesn't run scripts when installing packages.min-release-age=7ignore-scripts=truesave-exact=truePiece by piece:
- The lines with
#are comments. min-release-age=7: npm only installs versions published at least 7 days ago. Bad ones are usually pulled within hours or days: by the time they’d reach you, they’re gone.ignore-scripts=true: a package can bring a command that npm runs when installing it, with your permissions. That’s how Shai-Hulud got in. With this line, npm runs none of them. Yournpm testandnpm startstill work.save-exact=true: npm writes"1.1.1", without^. The version only changes when you decide.
It has a price: an urgent fix also waits a week, and the few packages that need their install command don’t work (none in this course). This site’s repository does the first two with pnpm, its package manager.
Try it
Section titled “Try it”The goal: turn your folder into an npm project, with a second program that reads from the disk and an .npmrc that installs packages carefully. Along the way you’ll break a program and fix it.
Work in the folder from the introduction, ~/backend-course/phase-3/shop-api, where your hello.js already is. The outputs are from Node 26.11.1 and npm 11.20.0 on Linux, with a Mac’s paths (on Linux and WSL they start with /home/ana); your versions, times and numbers may be different.
1. Open the REPL
nodeWhat you will see:
Welcome to Node.js v26.11.1.Type ".help" for more information.> 2 + 35> "hello".toUpperCase()'HELLO'> process.platform'linux'> windowUncaught ReferenceError: window is not defined> documentUncaught ReferenceError: document is not defined> .exitType each line after the > and press Enter. toUpperCase() turns text into capital letters, and process.platform says which system Node is running on: on your Mac, 'darwin'; on Linux and WSL, 'linux'.
window and document, the browser’s window and page, don’t exist here (is not defined). .exit closes the REPL.
Create products.json and read-products.js in your folder, with the code above, the same way you created hello.js.
2. Read a file from the disk
cd ~/backend-course/phase-3/shop-apinode read-products.jsWhat you will see:
The shop has 3 products:- T-shirt: 20 €- Mug: 8.5 €- Hoodie: 35 €If you get ENOENT: no such file or directory, open 'products.json', Node can’t find products.json in the folder you start the program from: it’s a relative path, like the ones in lesson 1 of Phase 1. Check with ls that you saved it in shop-api, with that name.
3. Create the npm project
npm init -yWhat you will see:
Wrote to /Users/ana/backend-course/phase-3/shop-api/package.json:
{"name": "shop-api","version": "1.0.0","description": "","main": "hello.js","scripts": { "test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC","type": "commonjs"}-y accepts the default answers without asking. Fields like description or license only matter if you publish the package. It isn’t the same as the package.json in the lesson’s folder, and that’s fine: what matters now is the last line, "type": "commonjs".
4. Read the products again
node read-products.jsWhat you will see:
(node:52) Warning: Failed to load the ES module: /Users/ana/backend-course/phase-3/shop-api/read-products.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.(Use `node --trace-warnings ...` to show where the warning was created)/Users/ana/backend-course/phase-3/shop-api/read-products.js:2import { readFile } from 'node:fs/promises';^^^^^^
SyntaxError: Cannot use import statement outside a module at wrapSafe (node:internal/modules/cjs/loader:1900:18) …
Node.js v26.11.1The same program, and now it fails. Without package.json, Node saw the import and understood it was a module. Now package.json tells it "commonjs", the old system, which doesn’t know import.
The warning on the first line gives the fix: "type": "module". We’ve removed the lines after wrapSafe, which say in which part of Node the error was raised. Your process number, the 52, will be different.
5. Fix it
npm pkg set type=modulenode read-products.jsWhat you will see:
The shop has 3 products:- T-shirt: 20 €- Mug: 8.5 €- Hoodie: 35 €npm pkg set changes a field of package.json without opening it. npm writes nothing if it goes well.
Before installing anything, create the .npmrc file in the folder, with the lines of the .npmrc above. Then install picocolors, a small package that colors the terminal’s text, with its exact version:
6. Install a package
npm install picocolors@1.1.1What you will see:
added 1 package, and audited 2 packages in 392ms
found 0 vulnerabilitiesadded 1 package is picocolors, which doesn’t need any others. audited 2 packages counts your project and it: npm looks for known security flaws, and there are none (0 vulnerabilities).
7. See what has changed
ls node_modulesgrep -A2 '"dependencies"' package.jsonWhat you will see:
picocolors"dependencies": { "picocolors": "1.1.1"}grep -A2 shows the line it looks for and the two after it. The version has no ^, because of save-exact. If you see "^1.1.1", npm hasn’t read your .npmrc: check its name, with the dot, and that it’s in shop-api. In package-lock.json you’ll see the version, where it came from (resolved) and its hash (integrity).
Challenge: delete node_modules with rm -rf node_modules. Does read-products.js still work? How do you get picocolors back with a short command, without typing its name or its version?Show answer
read-products.js still works: it only uses node:fs/promises, which comes with Node. To get picocolors back, npm install, with nothing else, which reads the lockfile:
added 1 package, and audited 2 packages in 338ms
found 0 vulnerabilitiesThat’s why node_modules isn’t saved in Git: with the lockfile, it’s created again exactly the same.
To finish, remove picocolors: the 01-node folder doesn’t use it.
8. Uninstall it
npm uninstall picocolorsWhat you will see:
removed 1 package, and audited 1 package in 130ms
found 0 vulnerabilitiesnpm deletes it from node_modules, from package.json and from the lockfile. The node_modules folder stays, with no packages.
If something doesn’t add up, download this lesson’s folder and compare it with yours: from ~/backend-course/phase-3, curl -O https://backenddesdecero.com/practicas/shop-api/01-node.tar.gz, tar -xzf 01-node.tar.gz and, inside, npm install and npm test.
You have already seen it
Section titled “You have already seen it”- This website. Its pages are generated by Astro, a Node program, before they’re published.
- VS Code. It’s built with Electron, which has Chromium and Node.js inside: that’s why an editor can read your files with JavaScript.
npm run dev. If you’ve ever started a website on your computer with this command, you were using Node and npm:devis one of thescriptsin itspackage.json.
Common mistakes
Section titled “Common mistakes”- Typing
node hello.jsinside the REPL. The REPL only understands JavaScript, and answersUncaught SyntaxError: Unexpected identifier 'hello'. Leave with.exitand type it in the terminal. - Using
windowordocumentin Node (is not defined): it’s code meant for a web page. Cannot use import statement outside a module."type": "module"is missing frompackage.json.- Saving
node_modulesin Git, or deleting the lockfile to “fix” something. The first fills the repository with other people’s code; the second loses the exact versions. - Asking for a version less than 7 days old. The
.npmrcanswersNo matching version found for typescript@7.1.0-dev.20261013.1 with a date before 10/6/2026, 10:51:50 AM.: it exists, but it’s too new. Ask for an earlier one, or wait.
Summary
Section titled “Summary”- Node.js runs JavaScript outside the browser with V8, Chrome’s engine, and adds files, network and processes, but not the page (
window,document). nodealone opens the REPL, to try single lines;node file.jsruns a program. Each file is a module, andimportbrings in pieces from others.- npm installs packages from a catalog where anyone can publish.
package.jsonsays what your project uses,node_modulesholds it and the lockfile pins the exact versions. - The project’s
.npmrcwaits 7 days for every new version, runs no commands when installing and saves exact versions: what the 2025 attacks taught.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Introduction to Node.js: the official guide.
- Differences between Node.js and the browser.
- JavaScript modules (MDN):
importandexport, with examples. - package.json and package-lock.json (npm): all their fields.
- Our plan for a more secure npm supply chain (GitHub): what npm changed after Shai-Hulud.