Node.js Tutorial

Build server-side JavaScript — modules, the file system, Express, and a REST API.

1 min read 147 words Updated Mar 9, 2026

Node.js runs JavaScript outside the browser. It’s event-driven and great for APIs and tooling.

Modules

// math.js
export function add(a, b) { return a + b; }

// app.js
import { add } from "./math.js";
console.log(add(2, 3));

Use "type": "module" in package.json to enable ESM.

Reading files

import { readFile } from "node:fs/promises";

const text = await readFile("data.txt", "utf8");
console.log(text);

A REST API with Express

import express from "express";

const app = express();
app.use(express.json());

const books = [{ id: 1, title: "Refactoring" }];

app.get("/books", (req, res) => res.json(books));
app.post("/books", (req, res) => {
  const book = { id: books.length + 1, ...req.body };
  books.push(book);
  res.status(201).json(book);
});

app.listen(3000, () => console.log("Listening on :3000"));

Use await at the top level only inside ESM modules or an async function.

Environment variables

import "dotenv/config";
const port = process.env.PORT || 3000;

Keep secrets out of source control — load them from .env.