Node.js Introduction

Learn what Node.js is and why it's used for servers and tools, install it, run JavaScript files from the terminal, use the REPL, and understand the event loop that makes Node fast.

Lesson 1 of 43Beginner17 min read

For most of its history, JavaScript only ran inside web browsers. Node.js changed that in 2009 by taking V8, the fast JavaScript engine from Google Chrome, and wrapping it in a program that runs on servers and personal computers. With Node, the same language that powers web pages can read files, talk to databases, run web servers and build command-line tools.

Node is used by companies of every size, from start-ups to Netflix, PayPal and LinkedIn, mainly for web APIs, real-time applications like chat and live dashboards, and developer tools. Many tools you may already use, such as npm, Vite, ESLint, Prettier and the TypeScript compiler, are themselves written in JavaScript and run on Node.

What makes Node special is its non-blocking design. When Node asks for a file or a database result, it doesn't sit and wait; it moves on to other work and comes back when the result is ready. That lets a single Node process handle thousands of connections at once. In this lesson you'll install Node, run your first scripts, try the interactive REPL, and learn how the event loop works.

Installing and running Node

  1. Download the LTS (Long Term Support) version from nodejs.org, or use a version manager such as nvm or fnm to switch between versions easily.
  2. Check the installation in a terminal:
Terminal
node --version      # for example v22.11.0
npm --version
  1. Create a file called hello.js and run it:
Terminal
node hello.js

Typing node on its own starts the REPL (Read-Eval-Print Loop), where you can type JavaScript and see results immediately. Press Ctrl+C twice, or type .exit, to leave.

Node versus the browser

Browser JavaScriptNode.js
window, document, the DOMNo DOM; globalThis and process instead
Talks to the page and the userTalks to files, networks, databases and the operating system
Runs in a sandbox for safetyHas full access to the machine it runs on
<script type="module"> and importsES modules (import) and older CommonJS (require)

The language itself is identical: variables, functions, arrays, objects, promises and classes all work the same. Node adds built-in modules such as fs for files, path for file paths, http for servers and os for system information. Modern Node also includes browser-style APIs like fetch, URL and setTimeout.

The event loop

Node runs your JavaScript on a single thread. Slow operations, such as reading a file or waiting for a network reply, are handed off to the system, and Node keeps running other code. When an operation finishes, its callback (or promise) is queued, and the event loop runs it as soon as the current code is done.

This is why the order of output can surprise you: code that schedules work with setTimeout or reads a file asynchronously finishes after the synchronous code below it, even with a delay of zero.

Node.js Basics Syntax

Running Node

node --version
node app.js
node --watch app.js      # rerun automatically when the file changes
node                     # start the REPL
node -e "console.log(2 + 3)"

Node.js Basics Summary

  • Node.js runs JavaScript outside the browser using Chrome's V8 engine.
  • It's used for web APIs, real-time apps and developer tools.
  • Run files with node file.js; type node alone for the interactive REPL.
  • Node has no DOM, but adds built-in modules like fs, path, http and os.
  • Node is non-blocking: slow work runs in the background and the event loop runs callbacks when it finishes.

Node.js Basics Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Hello from Node

Node.js
console.log('Hello from Node.js!');
console.log('Node version:', process.version.startsWith('v'));
console.log('Running on a', typeof window === 'undefined' ? 'server' : 'browser');

const items = ['files', 'servers', 'tools'];
for (const item of items) {
  console.log(`Node is great for ${item}`);
}
Output
Hello from Node.js!
Node version: true
Running on a server
Node is great for files
Node is great for servers
Node is great for tools
Line-by-line explanation
  1. Line 1console.log prints to the terminal instead of the browser's console.
  2. Line 2process is a global object with information about the running program; process.version is a string such as v22.11.0.
  3. Line 3There is no window object in Node.
  4. Lines 5 to 8Ordinary JavaScript works exactly as in the browser.
Example 2

The event loop in action

Node.js
console.log('1. Start');

setTimeout(() => {
  console.log('4. Timer finished');
}, 0);

Promise.resolve().then(() => {
  console.log('3. Promise callback');
});

console.log('2. End of script');
Output
1. Start
2. End of script
3. Promise callback
4. Timer finished
Line-by-line explanation
  1. Lines 3 to 5Even a zero-millisecond timer runs only after the current script finishes.
  2. Lines 7 to 9Promise callbacks run before timers, as soon as the current code is done.
  3. Line 11Synchronous code always runs first, top to bottom.
Example 3

Built-in information about the system

Node.js
import os from 'node:os';

const gb = (bytes) => (bytes / 1024 ** 3).toFixed(1);

console.log(`Platform: ${['win32', 'darwin', 'linux'].includes(os.platform()) ? 'known' : 'other'}`);
console.log(`CPU cores available: ${os.cpus().length > 0}`);
console.log(`Memory in GB is a number: ${!Number.isNaN(Number(gb(os.totalmem())))}`);
console.log(`Arguments after the script: ${JSON.stringify(process.argv.slice(2))}`);
Output
Platform: known
CPU cores available: true
Memory in GB is a number: true
Arguments after the script: []
Line-by-line explanation
  1. Line 1import loads a built-in module; the node: prefix makes it clear it's part of Node.
  2. Line 3An arrow function converts bytes to gigabytes.
  3. Line 5os.platform() returns win32, darwin (macOS) or linux.
  4. Line 8process.argv holds the command-line arguments; the first two are Node and the script path.

Common Node.js Basics Mistakes

Using browser objects in Node

Don't
document.querySelector('h1');     // ReferenceError: document is not defined
Do
import { readFile } from 'node:fs/promises';
const html = await readFile('index.html', 'utf8');   // work with files instead

Expecting a timer to run immediately

Don't
let ready = false;
setTimeout(() => { ready = true; }, 0);
console.log(ready);               // false: the timer hasn't run yet
Do
setTimeout(() => {
  console.log('Ready now');
}, 0);

Blocking the event loop

Don't
const end = Date.now() + 5000;
while (Date.now() < end) {}       // nothing else can run for five seconds
Do
setTimeout(() => console.log('Five seconds later'), 5000);

Node.js Basics in Real Projects

Where Node.js runs

Node powers the back ends of streaming services, online shops and banking apps, often as many small services behind an API gateway. It runs serverless functions on AWS Lambda, Vercel and Netlify, real-time features like chat and notifications, and the build tools behind almost every modern front-end project. Its huge package ecosystem, npm, means there's a well-tested library for nearly every task.

Node.js Basics FAQ

Is Node.js a programming language or a framework?

Neither. Node.js is a runtime: a program that runs JavaScript outside the browser, using Chrome's V8 engine plus built-in modules for files, networking and processes. The language is ordinary JavaScript, and frameworks such as Express or Fastify are packages you install on top of Node.

Is Node.js really single-threaded?

Your JavaScript runs on one main thread, so two of your functions never run at the same moment. Underneath, Node uses the operating system's asynchronous features and a small pool of helper threads (four by default) for work such as file access, compression and some crypto. When you need to run CPU-heavy JavaScript in parallel, you can start extra threads yourself with worker_threads.

How do I make Node restart my script automatically when I save?

Run it with the built-in watch mode: node --watch app.js. Node restarts the process whenever the file, or a module it imports, changes. Older projects often use the nodemon package for the same job, but recent Node versions no longer need it.

Can Node.js run TypeScript files directly?

Recent versions can. From Node 22.18, running node app.ts works for most code because Node strips the type annotations before running it; it doesn't check the types, so you still run tsc for that. On older versions, you compile with tsc first or use a runner such as tsx.

What is Node.js used for, and when is it a poor fit?

Node is a strong choice for web APIs, real-time apps, command-line tools and anything that spends most of its time waiting on networks, files or databases. It's a weaker fit for long CPU-heavy calculations, such as video encoding or large numeric simulations, because they block the single JavaScript thread unless you move them to worker threads or another language.

Node.js Basics Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the command that runs a file called app.js.

 app.js
Multiple choiceeasy

Which engine does Node.js use to run JavaScript?

Predict the outputmedium

What does this print?

setTimeout(() => console.log('A'), 0);
console.log('B');
Multiple choicemedium

Which of these doesn't exist in Node.js by default?

Multiple choicehard

Why can one Node process handle many connections at once?

Node.js Basics Quiz

5 questions to check what you learned.

  1. What does REPL stand for?

    • Run Every Program Line
    • Remote Execution Process Layer
    • Repeat Each Previous Line
    • Read-Eval-Print Loop
  2. Which Node versions are recommended for production?

    • Odd-numbered Current releases
    • LTS (Long Term Support) releases
    • Nightly builds
    • Any version
  3. What does process.argv contain?

    • Environment variables
    • The current directory
    • The command-line arguments
    • The Node version
  4. Which runs first?

    • A Promise .then callback
    • A setTimeout callback with 0 ms
    • They run at the same time
    • It's random
  5. What happens if your code runs a long synchronous loop?

    • The event loop is blocked, so no other requests or callbacks can run
    • Node runs it on another thread
    • Node stops the loop automatically
    • Nothing special