Node.js lets you run JavaScript outside a browser, so you can build servers and command-line tools with it. This Node JS tutorial takes you from one file to a working API that can list, add and delete notes. You need to know JavaScript variables, functions, arrays and objects.
Node.js is a runtime, not a language or a framework. A runtime is the program that executes your code. It also gives your JavaScript access to files, networks and the operating system.
Node JS tutorial setup and first file
Install the current LTS version from the official Node.js site. LTS means long-term support, which is a safe choice for learning and work. Check it:
node --version
npm --version
Make a folder and create a project:
mkdir notes-api
cd notes-api
npm init -y
npm pkg set type=module
package.json stores the project name, scripts and installed packages. The last command turns on modern import syntax. Create hello.js:
const name = process.argv[2] ?? "student";
console.log(`Hello, ${name}`);
node hello.js Meena
Output:
Hello, Meena
process.argv holds the command and its extra words. The first extra word is at index 2.
| Browser JavaScript | Node.js JavaScript |
|---|---|
Has document and page buttons |
Has no web page |
| Limited access to local files | Can read and write allowed files |
| Runs in the visitor's browser | Runs on your computer or server |
| Uses browser storage | Often uses files or a database |
Modules and npm packages
A module is a file that shares selected code. Create math.js:
export function add(a, b) {
return a + b;
}
Then create use-math.js:
import { add } from "./math.js";
console.log(add(4, 6));
It prints 10. Keep the ./ and .js in the path. Node also has built-in modules, such as node:fs for files and node:http for servers.
npm installs code written by others. npm install express, for example, downloads Express and records it in package.json. The exact versions are recorded in package-lock.json. Commit both files, but do not commit the node_modules folder.
Pro tip: Before you install a package, check whether Node already has the feature. Built-in modules now cover HTTP requests, tests, files and password hashing.
Async code and files
Reading a file takes time. Node can do other work while it waits. Use promises with async and await. Put this in files.js:
import { readFile, writeFile } from "node:fs/promises";
try {
await writeFile("note.txt", "Learn Node today", "utf8");
const text = await readFile("note.txt", "utf8");
console.log(text);
} catch (error) {
console.error("File error:", error.message);
}
Output:
Learn Node today
await pauses this module until the promise finishes. It does not mean the whole Node program is asleep. The catch block handles errors such as a missing folder.
Now look at the order of normal, promise and timer work:
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("normal");
Output:
normal
promise
timer
Normal code finishes first. Ready promise work runs next, then the timer gets its turn. The event loop is the part of Node that decides which waiting work runs.
Node usually runs your JavaScript on one main thread. Long loops block other requests. Waiting for a network or database does not need to block them. This is why Node suits programs that do a lot of waiting.
Build a server without a framework
Create server.js:
import { createServer } from "node:http";
const server = createServer((req, res) => {
if (req.method === "GET" && req.url === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok" }));
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Not found" }));
});
server.listen(3000, () => {
console.log("Open http://localhost:3000/health");
});
Run node server.js and open the printed address. You see {"status":"ok"}. Any other path gets status code 404. Press Ctrl+C to stop the server.
req describes the request. res lets you send the response. The server keeps running because it listens for more requests. Read what a REST API is if methods and status codes are new to you.
Build a notes API with Express
Express makes routes and JSON input easier. Install it:
npm install express
Create app.js:
import express from "express";
const app = express();
app.use(express.json());
let nextId = 1;
let notes = [];
app.get("/notes", (req, res) => {
res.json(notes);
});
app.post("/notes", (req, res) => {
const value = req.body?.text;
const text = typeof value === "string" ? value.trim() : "";
if (text === "") {
return res.status(400).json({ error: "text is required" });
}
const note = { id: nextId++, text };
notes.push(note);
res.status(201).json(note);
});
app.delete("/notes/:id", (req, res) => {
const id = Number(req.params.id);
const found = notes.some((note) => note.id === id);
if (!found) {
return res.status(404).json({ error: "Note not found" });
}
notes = notes.filter((note) => note.id !== id);
res.status(204).end();
});
const port = process.env.PORT ?? 3000;
app.listen(port, () => console.log(`Server on port ${port}`));
Start it with node --watch app.js. Node restarts the app when a file changes. Use an API tool such as Postman to send these requests:
| Method and path | JSON body | Expected status |
|---|---|---|
GET /notes |
None | 200 |
POST /notes |
{"text":"Read"} |
201 |
POST /notes |
{"text":""} |
400 |
DELETE /notes/1 |
None | 204 |
DELETE /notes/99 |
None | 404 |
The notes live in memory, so a restart erases them. For saved data, connect a database. The MongoDB tutorial shows the create, read, update and delete commands.
Common mistake: Forgetting
app.use(express.json())leaves the JSON body unread. The route then has no text to use.
Handle settings, errors and tests
Do not write a password or secret key in your code. Read it from an environment variable:
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
throw new Error("DATABASE_URL is missing");
}
This code fails early with a clear message. Put local settings in a .env file and add that file to .gitignore. Recent Node versions can load it with node --env-file=.env app.js.
Node has a built-in test tool. Create math.test.js:
import test from "node:test";
import assert from "node:assert/strict";
import { add } from "./math.js";
test("adds two numbers", () => {
assert.equal(add(4, 6), 10);
});
Run node --test. The report should show one passing test. Test bad input as well as good input. For the notes API, send an empty text, a missing text and an ID that does not exist.
Interview note: Do not say "Node is single-threaded" and stop. Say that JavaScript normally uses one main thread, while the system and a worker pool handle some other work. Worker threads can run heavy JavaScript separately.
Learn Node JS step by step
Use this order to learn Node JS from scratch:
- JavaScript base: functions, objects, array methods and promises.
- Node base: modules, npm, files, arguments and errors.
- HTTP: methods, paths, headers, JSON and status codes.
- Express: routes, middleware and checking input.
- Database: save the notes and handle connection errors.
- Login and safety: hashed passwords, sessions or tokens, and access checks.
- Tests and release: automatic tests, logs and deployment.
Do not try all seven at once. The simplest way to learn Node JS for beginners is to finish the notes API first. Then add an edit route, a search query and a database. Each addition teaches one clear skill.
This Node JS tutorial for beginners has reached its goal when you can explain how a request moves from the route to the response. To learn Node JS well, rebuild it without looking.
Next, connect the API to the React task app, check yourself with Node JS interview questions, or compare this path with the MERN stack program.
Frequently Asked Questions
Is Node.js a programming language?
Do I need React before Node.js?
Is Express the same as Node.js?
Which database should I use with Node.js?
Is Node.js good for heavy calculations?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — See the Java Full Stack course in Hyderabad

