Home › Programming › Node.js

Node.js

Node.js takes JavaScript out of the browser and onto the server — where it reads files, talks to databases, and serves HTTP.

Node.js is JavaScript with the browser swapped out for the operating system. The same language you use for page scripts now reads files, opens network sockets, and runs servers.

Running code

$ node app.js        # run a file
$ node               # interactive REPL

Modules

Code is split into modules. Modern Node uses ES modules:

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

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

You will also see the older CommonJS style (require() and module.exports) in lots of existing code.

npm

npm is the package manager. package.json records your project’s dependencies:

$ npm init -y            # create package.json
$ npm install express    # add a dependency
$ npm run start          # run a script you defined

A minimal HTTP server

import { createServer } from "node:http";

const server = createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello from Node
");
});

server.listen(3000, () => console.log("listening on :3000"));

In real projects you would usually reach for a framework like Express or Fastify to handle routing and parsing for you.

Why it is popular for servers

Watch out: because Node runs your callbacks on a single main thread, a heavy synchronous loop blocks everyone. Keep CPU-heavy work off the main thread or push it to a worker.

Keep reading