Your First Node.js Program: Hello World Explained

Your First Node.js Program: Hello World Explained
Writing "Hello, World!" is a rite of passage in every language. But in Node.js, even a three-line script touches the runtime in ways that are worth understanding deeply. In this module you will write your first Node.js program, explore the REPL, learn how Node.js executes your code, and meet the global objects every Node.js developer uses daily.
This is Module 3 of the Node.js Full‑Stack Developer course. If you have not installed Node.js yet, start with Module 2: Installing Node.js and npm.
The Node.js REPL: Instant JavaScript
Before creating a file, meet the REPL — your fastest way to experiment with Node.js.
Type node in your terminal with no arguments:
nodeYou will see a > prompt. This is a live JavaScript environment — type any expression and it evaluates immediately:
> 2 + 2
4
> "Hello, " + "World!"
'Hello, World!'
> Math.pow(2, 10)
1024
> new Date()
2026-05-12T10:00:00.000ZUseful REPL Commands
| Command | Action |
|---|---|
.help | Show all REPL commands |
.exit | Exit the REPL (or press Ctrl+C twice) |
.clear | Reset the REPL context |
.editor | Enter multi-line editor mode |
Tab | Auto-complete methods and properties |
The REPL is excellent for testing a quick function, checking an API method, or debugging a small expression. Use it constantly.
To exit the REPL, press Ctrl+C twice or type .exit.
Writing Your First Node.js Script
Now let us create a proper file. In your terminal:
mkdir hello-node && cd hello-nodeCreate a file called index.js and add this:
console.log("Hello, World!")Run it:
node index.jsOutput:
Hello, World!That is it — three tokens and you have a running Node.js program. But there is a lot happening underneath. Let us unpack it.
How Node.js Executes Your Code
When you run node index.js, the following happens:
- Parsing — Node.js reads
index.jsand passes the source code to the V8 engine, which parses it into an Abstract Syntax Tree (AST). - Compilation — V8 JIT-compiles the AST to native machine code. For a short script, this happens in microseconds.
- Execution — V8 executes the compiled code on the main thread.
- Event loop check — After your code runs, Node.js checks if there are any pending async operations (timers, I/O callbacks). If not, the process exits.
For console.log("Hello, World!") there are no async operations, so the process exits immediately after printing.
You can see this lifecycle with a timer:
console.log("1 - Script starts")
setTimeout(() => {
console.log("3 - Timer fires after 1 second")
}, 1000)
console.log("2 - Script ends (but process stays alive for timer)")Output:
1 - Script starts
2 - Script ends (but process stays alive for timer)
3 - Timer fires after 1 secondNode.js keeps the process alive until the timer fires, then exits. This is the event loop in action — covered fully in Module 5: The Node.js Event Loop.
Global Objects in Node.js
Unlike browser JavaScript where window is the global object, Node.js has its own set of globals available in every file without needing to require anything.
console
The most-used global. You already know console.log() — here are the others:
console.log("Standard output") // stdout
console.error("Something went wrong") // stderr (shows in red in most terminals)
console.warn("This is a warning") // stderr
console.table([{ name: "Alice", age: 30 }, { name: "Bob", age: 25 }])
console.time("myTimer")
// ... some code ...
console.timeEnd("myTimer") // prints: myTimer: 0.123ms
console.dir({ a: 1, b: { c: 2 } }, { depth: null }) // deep object inspectprocess
The process object is one of the most important globals in Node.js. It gives you runtime information and control over the current process:
console.log(process.version) // 'v20.14.0'
console.log(process.platform) // 'darwin', 'linux', or 'win32'
console.log(process.cwd()) // current working directory
console.log(process.uptime()) // seconds since Node.js process started
console.log(process.memoryUsage()) // { rss, heapTotal, heapUsed, external }process.env — Environment Variables
// Access environment variables
console.log(process.env.NODE_ENV) // 'development', 'production', etc.
console.log(process.env.PATH) // your system PATH
// Set them when starting the process:
// NODE_ENV=production node index.jsYou will use process.env constantly for configuration — database URLs, API keys, port numbers. Never hardcode these values in your code.
process.argv — Command-Line Arguments
process.argv is an array of strings passed to Node.js when you run it:
console.log(process.argv)Run with: node index.js hello 42
Output:
[
'/path/to/node', // argv[0] — path to node binary
'/path/to/index.js', // argv[1] — path to your script
'hello', // argv[2] — first argument
'42' // argv[3] — second argument
]A practical example — a script that accepts a name argument:
const name = process.argv[2] || "World"
console.log(`Hello, ${name}!`)node index.js Alice
# Hello, Alice!
node index.js
# Hello, World!process.exit() — Terminate the Process
if (!process.env.API_KEY) {
console.error("Error: API_KEY environment variable is required")
process.exit(1) // exit with error code 1
}
// Exit code 0 = success, 1+ = error
// process.exit(0) is the default when a script finishes normally__dirname and __filename
These are not technically globals in ES Modules, but they are available in CommonJS (the default for .js files):
console.log(__dirname) // absolute path to the directory of this file
console.log(__filename) // absolute path to this file itselfExample output:
/Users/alice/projects/hello-node
/Users/alice/projects/hello-node/index.jsYou will use __dirname constantly when building file paths (more on this in Module 7: Working with the Node.js File System).
setTimeout, setInterval, clearTimeout, clearInterval
These work identically to their browser counterparts:
// Run once after delay
const timer = setTimeout(() => {
console.log("Runs once after 2 seconds")
}, 2000)
// Run repeatedly
const interval = setInterval(() => {
console.log("Runs every second")
}, 1000)
// Stop the interval after 5 seconds
setTimeout(() => {
clearInterval(interval)
console.log("Interval stopped")
}, 5000)setImmediate
A Node.js-specific timer that runs after the current event loop iteration completes, but before any setTimeout with a delay of 0:
setImmediate(() => console.log("setImmediate fires"))
setTimeout(() => console.log("setTimeout 0 fires"), 0)
console.log("Synchronous code fires first")
// Output order:
// Synchronous code fires first
// setImmediate fires (usually)
// setTimeout 0 fires (usually)A More Complete First Program
Now let us combine everything into a slightly more interesting script:
// index.js
// 1. Display runtime info
console.log("=== Node.js Runtime Info ===")
console.log(`Node version : ${process.version}`)
console.log(`Platform : ${process.platform}`)
console.log(`Architecture : ${process.arch}`)
console.log(`Working dir : ${process.cwd()}`)
console.log(`Script path : ${__filename}`)
// 2. Read a command-line argument
const language = process.argv[2] || "Node.js"
console.log(`\nHello from ${language}!`)
// 3. Show memory usage
const mem = process.memoryUsage()
console.log(`\n=== Memory Usage ===`)
console.log(`Heap used : ${Math.round(mem.heapUsed / 1024 / 1024)} MB`)
console.log(`Heap total: ${Math.round(mem.heapTotal / 1024 / 1024)} MB`)
console.log(`RSS : ${Math.round(mem.rss / 1024 / 1024)} MB`)
// 4. Async example
console.log("\nStarting 1-second timer...")
setTimeout(() => {
console.log("Timer complete. Process will exit now.")
}, 1000)Run it:
node index.js JavaScriptSample output:
=== Node.js Runtime Info ===
Node version : v20.14.0
Platform : darwin
Architecture : arm64
Working dir : /Users/alice/projects/hello-node
Script path : /Users/alice/projects/hello-node/index.js
Hello from JavaScript!
=== Memory Usage ===
Heap used : 4 MB
Heap total: 8 MB
RSS : 38 MB
Starting 1-second timer...
Timer complete. Process will exit now.This single script touches the REPL, the process object, globals, command-line arguments, memory inspection, and async timers — the building blocks you will use across every Node.js application.
Watching Files with nodemon
During development, running node index.js manually after every change is tedious. Use nodemon (installed in Module 2) to auto-restart on file saves:
nodemon index.jsNow every time you save index.js, nodemon restarts it automatically. You will use this for the entire course.
CommonJS vs ES Modules: A Preview
Right now you are using CommonJS — the traditional Node.js module system where you require() things. In Module 4 you will learn the full module system. As a preview, here is the same program written in both styles:
CommonJS (default for .js files):
const os = require('os')
console.log(os.platform())ES Modules (requires "type": "module" in package.json or .mjs extension):
import os from 'os'
console.log(os.platform())Both work in modern Node.js. CommonJS is still the most common in backend code, but ES Modules are increasingly the standard — especially in frameworks like Next.js. You will use both throughout this course.
Node.js Full‑Stack Course — Module 3 of 32
You have written and understood your first Node.js program. Continue to Module 4 to master the Node.js module system — require, exports, and ES Modules.
Summary
In this module you wrote and dissected your first Node.js program. The key things to remember:
- Run any
.jsfile withnode filename.js - The REPL (
nodewith no args) is your instant JavaScript scratchpad - Node.js executes synchronous code first, then processes the event loop for async callbacks
- Global objects —
console,process,__dirname,__filename,setTimeout,setImmediate— are available in every Node.js file without importing process.envholds environment variables;process.argvholds command-line arguments- Use
nodemonduring development so files auto-restart on save
Continue to Module 4: Node.js Modules — require, exports, and ES Modules →
Content powered by SearchFit.ai — for automated content at scale, visit https://searchfit.ai
