Basics of Node.js

Node.js is a JavaScript runtime that lets you run JavaScript outside the browser.

Installation

Check that Node.js is installed:

node --version

Run JavaScript:

node

Or execute a file:

node index.js

A Simple Program

console.log("Hello, Node.js!");

Save as index.js and run:

node index.js

Modules

Node.js uses modules to organize code.

CommonJS

const fs = require("node:fs");

ES Modules

With "type": "module" in package.json:

import fs from "node:fs";

Built-in Modules

Node.js provides many built-in modules.

import path from "node:path";
import fs from "node:fs";

Some common modules:

Reading Files

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

const content = await readFile("hello.txt", "utf8");

console.log(content);

Writing Files

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

await writeFile("hello.txt", "Hello!");

Command-Line Arguments

console.log(process.argv);

Run:

node index.js hello world

Arguments are available in process.argv.

Environment Variables

console.log(process.env.NODE_ENV);

Set one from the shell:

NODE_ENV=production node index.js

package.json

Create a Node.js project:

npm init

Or:

pnpm init

A basic package.json:

{
  "name": "my-project",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  }
}

Run a script:

pnpm start

Installing Packages

Install a package:

pnpm add lodash

Install a development dependency:

pnpm add -D typescript

Import it:

import _ from "lodash";

HTTP Server

Node.js can create HTTP servers without external packages.

import { createServer } from "node:http";

const server = createServer((req, res) => {
  res.end("Hello!");
});

server.listen(3000);

Start it:

node index.js

Then visit:

http://localhost:3000

Asynchronous Code

Node.js APIs commonly use promises.

const result = await someAsyncFunction();

You can also use .then():

someAsyncFunction()
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error(error);
  });

Useful Globals

Some commonly used Node.js globals:

console.log(process);
console.log(process.cwd());
console.log(process.argv);
console.log(process.env);

globalThis is the global object:

console.log(globalThis);

Useful Commands

node file.js
node --watch file.js
node --help
node --version

--watch automatically restarts the program when files change:

node --watch index.js

Node.js vs Browser JavaScript

Browser JavaScript provides APIs such as:

document;
window;
localStorage;
fetch;

Node.js provides APIs such as:

process;
fs;
path;
Buffer;

fetch() is also available in modern Node.js.

Typical Project

my-project/
├── package.json
├── index.js
└── node_modules/

A common workflow:

pnpm init
pnpm add some-package
node index.js