Node.jsBackendFull-Stack

Your First Node.js Program: Hello World Explained

TT
TopicTrick Team
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:

bash
node

You will see a > prompt. This is a live JavaScript environment — type any expression and it evaluates immediately:

javascript
> 2 + 2
4
> "Hello, " + "World!"
'Hello, World!'
> Math.pow(2, 10)
1024
> new Date()
2026-05-12T10:00:00.000Z

Useful REPL Commands

CommandAction
.helpShow all REPL commands
.exitExit the REPL (or press Ctrl+C twice)
.clearReset the REPL context
.editorEnter multi-line editor mode
TabAuto-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:

bash
mkdir hello-node && cd hello-node

Create a file called index.js and add this:

javascript
console.log("Hello, World!")

Run it:

bash
node index.js

Output:

text
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:

  1. Parsing — Node.js reads index.js and passes the source code to the V8 engine, which parses it into an Abstract Syntax Tree (AST).
  2. Compilation — V8 JIT-compiles the AST to native machine code. For a short script, this happens in microseconds.
  3. Execution — V8 executes the compiled code on the main thread.
  4. 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:

javascript
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:

text
1 - Script starts
2 - Script ends (but process stays alive for timer)
3 - Timer fires after 1 second

Node.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:

javascript
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 inspect

process

The process object is one of the most important globals in Node.js. It gives you runtime information and control over the current process:

javascript
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

javascript
// 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.js

You 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:

javascript
console.log(process.argv)

Run with: node index.js hello 42

Output:

javascript
[
  '/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:

javascript
const name = process.argv[2] || "World"
console.log(`Hello, ${name}!`)
bash
node index.js Alice
# Hello, Alice!

node index.js
# Hello, World!

process.exit() — Terminate the Process

javascript
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):

javascript
console.log(__dirname)   // absolute path to the directory of this file
console.log(__filename)  // absolute path to this file itself

Example output:

text
/Users/alice/projects/hello-node
/Users/alice/projects/hello-node/index.js

You 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:

javascript
// 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:

javascript
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:

javascript
// 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:

bash
node index.js JavaScript

Sample output:

text
=== 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:

bash
nodemon index.js

Now 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):

javascript
const os = require('os')
console.log(os.platform())

ES Modules (requires "type": "module" in package.json or .mjs extension):

javascript
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 .js file with node filename.js
    • The REPL (node with no args) is your instant JavaScript scratchpad
    • Node.js executes synchronous code first, then processes the event loop for async callbacks
    • Global objectsconsole, process, __dirname, __filename, setTimeout, setImmediate — are available in every Node.js file without importing
    • process.env holds environment variables; process.argv holds command-line arguments
    • Use nodemon during 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