Node.js Tutorial for JavaScript Developers, Step by Step

Node.js is a JavaScript runtime environment built on Chrome’s V8 engine. It runs JavaScript outside the browser, on your computer or a server. If you already know browser JavaScript, start by installing an LTS (Long Term Support) release. Then save a file with a .js extension and run it with node file.js in a terminal. This tutorial walks you through that path in numbered steps, each with code and the output to expect.

How Node.js works in one minute

Node.js is open-source and cross-platform, so it runs on Windows, macOS and Linux. It is not a programming language or a web server. It is a runtime environment: a program that executes JavaScript code for you. That is why it is used for server-side work, meaning code that runs on a server instead of in the visitor’s web browser (the client side).

Your script goes to the node program, which uses V8 to compile and execute it. Instead of a page, a DOM and a window, you get access to the operating system through built-in modules. Examples are fs (files), http (network) and path (file paths). Node runs your code on a single main thread and hands slow work such as disk and network access to the system. This makes it non-blocking (it does not wait idle for slow tasks) and event-driven (it reacts when a task finishes). Step 6 explains this in detail.

Typical uses include web applications, REST APIs (services that exchange JSON data over HTTP), command-line tools, real-time apps such as chat, and scripts that work with files.

programming code laptop

Step 1: Install an LTS release

Go to nodejs.org and download the version labelled LTS. LTS releases receive fixes for a long period, so they suit learning and production. The “Current” release is meant for trying new features. The installer works on Windows, macOS and Linux, and a version manager such as nvm is a good option if you need several versions side by side.

Open a terminal (Command Prompt, PowerShell or a Unix shell) and check the installation:

node --version
npm --version

Expected output: two version numbers. They will match the release you installed. If you see “command not found”, close and reopen the terminal so the PATH (the list of folders where the system looks for programs) is refreshed.

Step 2: Run your first script

Create a folder, then a file named hello.js. This is the classic Hello World program:

console.log('Hello from Node.js');
console.log(2 + 3);

Run it with the following command:

node hello.js

Expected output:

Hello from Node.js
5

You can also type node alone to open the REPL (read-eval-print loop), an interactive prompt where each line is evaluated immediately. Press Ctrl+C twice to leave it.

Step 3: Understand how Node differs from the browser

The language is the same, but the environment is not. This table shows what changes for a developer coming from the front end.

Topic Browser Node.js
Global object window globalThis (no window)
DOM and document Available Not available
Files and OS Blocked by the sandbox Available through fs, os, path
Modules ES modules ES modules and CommonJS
Main purpose Interfaces for users Servers, tools, scripts

The DOM (Document Object Model) is the browser’s tree representation of an HTML page. Node has no page, so calls like document.querySelector() or alert() cause errors. To see the difference yourself, run this:

console.log(typeof window);
console.log(typeof process);
console.log(process.platform);

Expected output on Linux: undefined, object, linux. The process object describes the running program. It is specific to Node.

a person sits in front of a laptop, working on code

Step 4: Use ES modules and npm

Create a project

npm (Node Package Manager) is installed with Node. It downloads libraries and records them in a package.json file, which describes your project and its dependencies.

npm init -y

Open the generated package.json and add "type": "module". This tells Node to treat .js files as ES modules, so you can use import and export as in the browser.

Write and import a module

A module is a file with reusable code that other files can import. Create math.js:

export function add(a, b) {
  return a + b;
}

Create app.js:

import { add } from './math.js';
import os from 'node:os';

console.log(add(2, 3));
console.log(os.platform());

Run node app.js. Expected output: 5 then your platform name, such as linux, darwin or win32. The node: prefix marks a built-in module and avoids confusion with npm packages. The older CommonJS style (require and module.exports) still exists, and you will meet it in many existing projects.

Install a package

npm install dayjs

This creates a node_modules folder and adds the package to dependencies in package.json. Do not commit node_modules to Git. Anyone can rebuild it with npm install.

Step 5: Work with files and async/await

Reading a file takes time, so Node offers an asynchronous, promise-based API in node:fs/promises. Asynchronous means the program starts the task and continues, then gets the result later. Create notes.txt containing Learning Node, then files.js:

import { readFile, writeFile } from 'node:fs/promises';

const text = await readFile('notes.txt', 'utf8');
console.log('Read:', text);

await writeFile('copy.txt', text.toUpperCase());
console.log('Copy written');

Expected output:

Read: Learning Node
Copy written

Top-level await works here because the file is an ES module. In a CommonJS file you would wrap the code in an async function. Other useful functions from the same module are mkdir, readdir, rename and unlink (delete). Synchronous versions such as readFileSync exist, but they are blocking: they stop the whole process until they finish. Keep them for start-up scripts.

Step 6: Understand the event loop

Node has one main thread that runs your JavaScript. When you start a slow operation, Node delegates it and keeps going. When the operation finishes, its callback (the function you passed to be called afterwards) is queued. The event loop runs it once the current code is done. Try this:

console.log('1: start');

setTimeout(() => console.log('3: timer'), 0);
Promise.resolve().then(() => console.log('2: promise'));

console.log('1b: end of script');

Expected output:

1: start
1b: end of script
2: promise
3: timer

Synchronous code runs first, then promise callbacks (the microtask queue), then timers. The practical consequence is that a long loop or heavy calculation blocks every other request. Keep that work out of your request handlers.

a photo showing two adults at a bright desk

Step 7: Build a small HTTP API

The built-in http module is enough for a first web server, with no framework. Create server.js:

import { createServer } from 'node:http';

const todos = [{ id: 1, title: 'Learn Node.js' }];

const server = createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/todos') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(todos));
    return;
  }
  res.writeHead(404, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ error: 'Not found' }));
});

server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

Run node server.js. Then, in a second terminal, run:

curl http://localhost:3000/todos

Expected output: [{"id":1,"title":"Learn Node.js"}]. Any other path returns {"error":"Not found"} with status 404. The req object describes the request (method, URL, headers). The res object builds the response. JSON.stringify converts a JavaScript object into a JSON string. Stop the server with Ctrl+C.

The same idea with Express

Express is the most widely used web framework for Node. It adds routing (matching a URL to a handler) and middleware (functions that process a request before the final handler). It also serves static files such as HTML, CSS and images. Install it with npm install express, then create express-server.js:

import express from 'express';

const app = express();
app.use(express.static('public'));

app.get('/', (req, res) => res.send('Hello World!'));

app.listen(3000);

Open http://localhost:3000 and you see Hello World!. Any file you place in a public folder can be requested by the browser.

Step 8: Handle errors and read environment variables

Catch errors

With async/await, use try/catch:

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

try {
  await readFile('missing.txt', 'utf8');
} catch (err) {
  console.error('Failed:', err.code);
}

Expected output: Failed: ENOENT. This is the code for “no such file or directory”. In the HTTP server, wrap handler logic in try/catch and answer with status 500. Otherwise an uncaught exception can stop the process.

Read environment variables

Configuration such as ports and secrets belongs outside the code. In server.js, add const port = process.env.PORT || 3000; before the call to listen. Use port in listen and in the log message, for example console.log(`Listening on http://localhost:${port}`). Then start it:

PORT=4000 node server.js

Expected output: Listening on http://localhost:4000. On Windows PowerShell, set the variable first with $env:PORT=4000. Never commit files containing secrets.

Common pitfalls

  • Symptom: Cannot use import statement outside a module. Cause: the project is still treated as CommonJS. Fix: add "type": "module" to package.json or rename the file to .mjs.
  • Symptom: EADDRINUSE when starting the server. Cause: another process already uses the port. Fix: stop the old process or choose another port.
  • Symptom: ERR_MODULE_NOT_FOUND on a local import. Cause: ES modules require the file extension. Fix: write ./math.js, not ./math.
  • Symptom: a file prints Promise { <pending> }. Cause: a missing await. Fix: await the call inside an async context.

What to learn next

  • Express or Fastify for routing and middleware
  • A database such as PostgreSQL or MongoDB with a driver or ORM (a layer that maps database rows to objects)
  • The built-in test runner (node:test)
  • Streams, for large files and real-time data
  • TypeScript with Node.js
  • Deployment, logging and process management

Recap

Node.js lets you reuse your JavaScript knowledge on the server: install an LTS release, run scripts, then rely on ES modules, npm and async/await for everyday work. Remember that the event loop favours non-blocking code, and that errors and configuration deserve attention from your first API. Rebuild the examples above from memory, then extend the todo API with a POST route to make the concepts stick.

Search

Recent Blog

  • All Post
  • Email Marketing
  • Responsive Website
  • SEO
  • Server Side
  • Social Media Marketing
  • Web Design
  • Web Development

Subscribe

You have been successfully Subscribed! Ops! Something went wrong, please try again.

Company Name

Gemini Web

Company Address

3444 Hall Valley Drive, Davy, WV 24828 USA

Company Email

[email protected]

Copyright © 2022 Gemini Web. All Rights Reserved.