Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 156 ยท Modules and Tooling

JavaScript on the Server with Node.js

Run JavaScript outside the browser with Node.js - process and argv, environment variables, fs/promises, path, a minimal HTTP server, npm scripts and ESM vs CommonJS.

Everything you've learned so far about the JavaScript language (variables, functions, objects, promises, modules) works outside the browser too. Node.js takes the V8 engine from Chrome, removes the page, and adds what a program on a computer or server needs: access to files, the network, environment variables and other processes. With it, the same language that powers buttons and forms runs web servers, APIs, command-line tools, build systems and automation scripts.

This lesson is a practical tour of Node.js for someone who already knows JavaScript: what's different from the browser, the handful of built-in modules you'll use constantly (process, fs, path, http), how projects are run with npm scripts, and how ES modules and CommonJS coexist. It ends with a short look at automation and scraping.

About the live editors. The editors on this site run in your browser, not in Node.js, so process, fs and http don't exist in them. Node-only code is shown read-only (paste it into a file and run it with node file.js if you have Node installed). The live examples cover the parts that are plain JavaScript: argument parsing, configuration, request handling and HTML parsing.

Node vs the browser

The language is identical; the host is not (the Running JavaScript lesson introduced this split). Here's what changes when you move to Node:

Browser Node.js
Global object window (also globalThis) globalThis (global in older code)
The page document, the DOM, alert() none
Storage localStorage, IndexedDB, cookies real files via node:fs, databases
Information about the run location, navigator process.argv, process.env, process.cwd()
Binary data Blob, typed arrays Buffer (a Uint8Array subclass), typed arrays
Shared by both console, timers, fetch, URL, TextEncoder, structuredClone, crypto.randomUUID(), AbortController
Security model sandboxed; can't touch your disk full access to whatever the user running it can access

That last row matters most. Browser code is boxed in so websites can't harm your computer. A Node program runs with all your permissions: it can delete files, read SSH keys or send data anywhere. Only run scripts and install packages you trust (see Packages, npm and Build Tools).

Because the shared list keeps growing, you can write a lot of code that runs in both places. When a module must behave differently per host, check for features with typeof rather than guessing:

JS Code that runs in any host

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The editor reports "a browser page". Save the same code as host.mjs and run node host.mjs, and it reports the Node version instead; the rest of the output is identical.

Running Node programs

After installing Node.js (pick the LTS version, which gets updates for about three years), a few commands cover daily use:

TEXT
node                       # an interactive REPL, like the browser console
node app.js                # run a file
node --watch app.js        # rerun automatically when files change
node --env-file=.env app.js  # load variables from a .env file first
node --test                # run tests with the built-in test runner

--watch, --env-file and the built-in node:test runner are newer conveniences (stable in Node 22 LTS and later) that replace small packages like nodemon and dotenv in many projects. Recent versions (22.18+ and 23.6+) can even run .ts files directly by stripping TypeScript's type annotations, though they don't type-check them.

The process object

process is a global that describes the running program and lets it talk to the operating system.

JavaScript
// Read-only: save as greet.mjs and run: node greet.mjs Ana --shout
console.log(process.argv);
// [ '/usr/local/bin/node', '/home/ana/greet.mjs', 'Ana', '--shout' ]

const [name = "world", ...flags] = process.argv.slice(2);
const text = `Hello, ${name}!`;
console.log(flags.includes("--shout") ? text.toUpperCase() : text);

console.log(process.cwd());         // the folder you ran the command from
console.log(process.platform);      // "linux", "darwin" (macOS) or "win32"
console.log(process.env.HOME);      // environment variables are strings (or undefined)

process.exitCode = 1;               // report failure when the program ends
  • process.argv is an array of strings: the path to node, the path to your script, then the arguments the user typed. slice(2) gives you just the arguments.
  • process.env holds environment variables: settings such as API keys, database URLs and the port to listen on, provided by the shell or the hosting platform instead of being written in the code.
  • process.exitCode (or process.exit(code)) tells the shell whether the program succeeded: 0 means success, anything else means failure. Scripts and CI pipelines rely on this. Prefer setting exitCode over calling process.exit(), which stops immediately, even in the middle of writing a file.
  • process.stdout.write(text) prints without adding a newline; process.stdin reads input piped into the program.

Parsing arguments is plain array work, so you can try it right here. For real tools, Node includes parseArgs in node:util, and packages like Commander handle subcommands and help text.

JS Parsing command-line arguments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Environment variables and configuration

Configuration that differs between your laptop and the server (ports, database URLs, secrets) belongs in environment variables, not in code. Read them once at startup, convert them from strings, apply defaults, and fail loudly if something required is missing. A crash on startup is much better than a mysterious failure an hour later.

JS Loading and validating configuration

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The comment on DEBUG points at the classic trap: process.env.DEBUG is the string "false", which is truthy (see Type Conversion). Never commit real secrets; keep a .env.example with placeholder values in the repository and the real .env out of it.

Files with fs/promises

Reading and writing files is the first thing most scripts do. Node's node:fs/promises module offers promise-based functions that work with async/await:

JavaScript
// Read-only: notes.mjs
import { readFile, writeFile, mkdir, readdir, stat } from "node:fs/promises";

const text = await readFile("notes.txt", "utf8");          // a string
const lines = text.split("\n").filter(Boolean);
console.log(`${lines.length} notes`);

await mkdir("out", { recursive: true });                    // no error if it exists
await writeFile("out/notes.json", JSON.stringify(lines, null, 2));

for (const name of await readdir(".")) {
  const info = await stat(name);
  console.log(info.isDirectory() ? "[dir] " : "      ", name, info.size);
}

try {
  await readFile("missing.txt", "utf8");
} catch (err) {
  if (err.code === "ENOENT") console.log("No such file");   // file not found
  else throw err;
}

A few things to know:

  • Pass an encoding such as "utf8" to get a string; without it you get a Buffer of raw bytes.
  • Errors have a code: ENOENT (doesn't exist), EACCES (permission denied), EEXIST (already exists). Check the code rather than the message.
  • The node: prefix marks built-in modules clearly (node:fs can never be confused with a package called fs). It's the recommended style.
  • There are also synchronous versions (readFileSync) in node:fs. They're fine in small scripts and startup code, but in a server they block every other request while the disk works, so use the promise versions there.
  • For very large files, read them in pieces with streams (createReadStream) instead of loading everything into memory at once.

Paths with node:path

File paths look different on Windows (C:\data\report.csv) and on macOS/Linux (/home/ana/data/report.csv). Never build them by gluing strings with "/". The node:path module does it correctly for the current operating system:

JavaScript
// Read-only
import path from "node:path";

path.join("data", "2026", "report.csv");   // "data/2026/report.csv" (or "data\\2026\\report.csv" on Windows)
path.resolve("data/report.csv");           // an absolute path, starting from process.cwd()
path.basename("/srv/app/photo.final.jpg"); // "photo.final.jpg"
path.extname("photo.final.jpg");           // ".jpg"
path.dirname("/srv/app/photo.jpg");        // "/srv/app"
path.parse("/srv/app/photo.jpg");          // { root, dir, base, ext, name }

// Paths relative to THIS file, not to where the user ran the command
const templates = path.join(import.meta.dirname, "templates");

That last line is important. Relative paths like "data.json" are resolved from the folder the user was in when they ran node, which is often not the folder your script lives in. import.meta.dirname (Node 20.11+) gives the folder of the current module; CommonJS files use __dirname instead.

A minimal HTTP server

Node's built-in node:http module can run a web server in a few lines. Every request calls your function with two objects: req (the incoming request: method, URL, headers, body) and res (the response you build: status, headers, body).

JavaScript
// Read-only: server.mjs, then open http://localhost:3000/api/hello?name=Ana
import { createServer } from "node:http";

const server = createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);

  if (req.method === "GET" && url.pathname === "/api/hello") {
    const name = url.searchParams.get("name") ?? "stranger";
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ message: `Hello, ${name}!` }));
    return;
  }

  res.writeHead(404, { "Content-Type": "text/plain" });
  res.end("Not found");
});

const port = Number(process.env.PORT ?? 3000);
server.listen(port, () => console.log(`Listening on http://localhost:${port}`));

The server keeps running and handles requests one after another on the single JavaScript thread. While it waits for a database or a file, the event loop serves other requests, which is why Node handles many simultaneous connections well, and also why a long CPU-heavy loop in a handler freezes every user.

Real projects add routing, body parsing and middleware with a framework such as Express, Fastify or Hono (see Where to Go Next), but the idea underneath is always this function. Because it's just a function, you can test the logic without a network by passing it fake objects:

JS A request handler tested with fake req and res

Press Run (or Ctrl + Enter) to see the console output here.

No output.

npm scripts and project setup

A Node project is a folder with a package.json (the tooling lesson explains its fields). Two settings matter most for writing Node code:

JSON
{
  "name": "inventory-api",
  "type": "module",
  "engines": { "node": ">=22" },
  "scripts": {
    "start": "node server.js",
    "dev": "node --watch --env-file=.env server.js",
    "test": "node --test",
    "import:csv": "node scripts/import.js data/products.csv"
  }
}
  • "type": "module" makes .js files ES modules, so you can use import/export everywhere.
  • scripts are named commands: npm run dev, npm run import:csv. npm start and npm test work without run. Scripts can call tools installed in node_modules/.bin by name, so "lint": "eslint ." works without a global install. Recent Node versions can also run scripts directly with node --run dev, which starts faster than npm.

ES modules vs CommonJS

Node existed years before JavaScript had standard modules, so it created its own format, CommonJS. Today Node supports both, and you'll meet both in real code:

ES modules (ESM) CommonJS (CJS)
Import import fs from "node:fs" const fs = require("node:fs")
Export export function f() {} module.exports = { f }
File is ESM when .mjs, or .js with "type": "module" .cjs, or .js without "type": "module"
Loading resolved before the code runs; top-level await allowed require() runs synchronously when reached
This file's folder import.meta.dirname __dirname
Works in browsers Yes No
JavaScript
// Read-only: the same small module in both formats

// math.mjs (ESM)
export const add = (a, b) => a + b;

// math.cjs (CommonJS)
const add = (a, b) => a + b;
module.exports = { add };

For new code, use ESM: it's the standard, it works in browsers and Node alike, and tools can remove unused exports from it. You can import a CommonJS package from ESM without any trouble. The other direction used to be impossible, but recent Node versions (20.19+ and 22.12+) can require() ES modules too, as long as they don't use top-level await.

Automation and scraping

Node is excellent for the small chores that would take an hour by hand: renaming hundreds of files, converting a CSV export, checking a list of links, or collecting data from web pages. Since Node 18, fetch() is built in, so a script can download a page and parse it:

JavaScript
// Read-only: headlines.mjs (run with: node headlines.mjs)
// HTML parsing uses the "cheerio" package: npm install cheerio
import * as cheerio from "cheerio";

const res = await fetch("https://news.example.com/", {
  headers: { "User-Agent": "headline-bot/1.0 (contact: [email protected])" },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);

const $ = cheerio.load(await res.text());
const headlines = $("article h2 a")
  .map((_, el) => ({ title: $(el).text().trim(), url: new URL($(el).attr("href"), res.url).href }))
  .get();

console.table(headlines.slice(0, 5));

Node has no DOM, so parsing HTML needs a package such as cheerio (jQuery-like selectors) or linkedom/jsdom (a DOM implementation). The browser has a parser built in, DOMParser, which uses exactly the same selector logic you learned in Selecting Elements. This demo parses a page that's stored in a string, the step a scraper does right after fetch():

Extracting data from fetched HTML

Scrape politely and legally. Check whether the site offers an API first; it's more reliable than parsing HTML that can change any day. Respect robots.txt and the site's terms of service, send an honest User-Agent, wait between requests (one per second or slower) and cache what you download. Don't collect personal data you have no right to process.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is available in Node.js but not in a browser page?

    process is a Node.js global describing the running program. fetch, URL and timers exist in both hosts.
  2. 2. You run node tool.js report.csv --dry-run. What does process.argv.slice(2) contain?

    argv starts with the node executable and the script path; slice(2) leaves only the user's arguments, as strings.
  3. 3. process.env.DEBUG is "false". What does if (process.env.DEBUG) do?

    Environment variables are always strings. Compare explicitly, for example process.env.DEBUG === "true".
  4. 4. Why should a server use readFile from node:fs/promises instead of readFileSync?

    Synchronous I/O stops the event loop. Fine in small scripts, harmful in a server handling many users.
  5. 5. Which file is treated as an ES module by Node.js?

    .mjs is always ESM and .cjs always CommonJS. A .js file is ESM only when the nearest package.json says "type": "module".

Summary

  • Node.js runs JavaScript outside the browser: no DOM, but files, network, processes and full access to the machine.
  • process gives you argv (arguments as strings), env (configuration), cwd() and exitCode. Validate configuration once at startup.
  • node:fs/promises reads and writes files with await; check err.code (such as ENOENT) when something fails.
  • node:path builds paths that work on every OS; use import.meta.dirname for paths relative to your module.
  • node:http runs a server where every request calls one handler function with req and res; frameworks build on top of it.
  • npm scripts in package.json name your project's commands; "type": "module" makes .js files ES modules.
  • Prefer ES modules for new code; CommonJS (require, module.exports) is still common in older packages.
  • Node is great for automation and scraping: fetch() the page, parse it with a library, and be polite to the sites you visit.

Next: The DOM โ€” start controlling web pages with JavaScript.