Your First Node.js Program
Time to write real code! In this lesson, you'll create your first Node.js programs, understand how to run them, and explore the Node.js REPL (Read-Eval-Print Loop) for quick experimentation.
Installing Node.js
Before writing code, you need Node.js installed on your computer:
- Visit nodejs.org
- Download the LTS (Long Term Support) version
- Run the installer and follow the prompts
- Verify installation by opening a terminal:
node --version
# Should output something like: v20.10.0
npm --version
# Should output something like: 10.2.3
If you see version numbers, you're ready to go!
Hello, Node.js!
Let's create the classic "Hello, World!" program:
Step 1: Create a File
Create a new file called hello.js:
// hello.js
console.log("Hello, Node.js!");
Step 2: Run It
Open your terminal, navigate to the file's directory, and run:
node hello.js
You should see:
Hello, Node.js!
Congratulations! You've just run your first Node.js program.
The Node.js REPL
Node.js includes a REPL (Read-Eval-Print Loop)—an interactive environment for experimenting with code:
# Start the REPL
node
# You'll see a prompt like:
>
Now you can type JavaScript and see immediate results:
> 2 + 2
4
> "hello".toUpperCase()
'HELLO'
> const name = "Node"
undefined
> `Hello, ${name}!`
'Hello, Node!'
> .exit // Type this to exit
Useful REPL Commands
| Command | Description |
|---|---|
.help | Show help |
.exit | Exit the REPL |
.clear | Clear context |
.save filename | Save session to file |
.load filename | Load file into REPL |
Understanding process
The process object is one of Node.js's most important globals. It provides information about the current Node.js process:
// process-info.js
// Node.js version
console.log("Node version:", process.version);
// Current working directory
console.log("Working directory:", process.cwd());
// Platform (darwin, win32, linux)
console.log("Platform:", process.platform);
// Process ID
console.log("Process ID:", process.pid);
// Memory usage
console.log("Memory usage:", process.memoryUsage());
Command Line Arguments
Node.js can receive arguments from the command line:
// greet.js
const args = process.argv;
console.log("All arguments:", args);
console.log("Node path:", args[0]);
console.log("Script path:", args[1]);
console.log("Your arguments:", args.slice(2));
Run it with arguments:
node greet.js hello world 123
Output:
All arguments: [ '/usr/local/bin/node', '/path/to/greet.js', 'hello', 'world', '123' ]
Node path: /usr/local/bin/node
Script path: /path/to/greet.js
Your arguments: [ 'hello', 'world', '123' ]
Building a Simple CLI Tool
Let's create a more practical program—a greeting CLI:
// cli-greet.js
const args = process.argv.slice(2);
const name = args[0] || "World";
const greeting = args[1] || "Hello";
console.log(`${greeting}, ${name}!`);
console.log(`The current time is: ${new Date().toLocaleTimeString()}`);
node cli-greet.js
# Hello, World!
node cli-greet.js Alice
# Hello, Alice!
node cli-greet.js Alice "Good morning"
# Good morning, Alice!
Environment Variables
Node.js can read environment variables from your system:
// env-example.js
// Access environment variables
console.log("HOME:", process.env.HOME);
console.log("PATH:", process.env.PATH);
console.log("NODE_ENV:", process.env.NODE_ENV);
// Set environment variables when running
// NODE_ENV=production node env-example.js
You can also set environment variables when running:
NODE_ENV=production API_KEY=secret123 node app.js
Exiting a Program
You can exit a Node.js program with process.exit():
// exit-example.js
console.log("Starting program...");
// Check for required argument
if (process.argv.length < 3) {
console.error("Error: Please provide an argument");
process.exit(1); // Exit with error code 1
}
console.log("Argument received:", process.argv[2]);
console.log("Program completed successfully");
process.exit(0); // Exit with success code 0
Exit codes:
- 0: Success (no errors)
- 1 or higher: Error occurred
Standard Input/Output
Node.js can read from standard input:
// echo.js
process.stdin.setEncoding('utf8');
console.log("Type something and press Enter:");
process.stdin.on('data', (input) => {
const trimmed = input.trim();
console.log(`You typed: ${trimmed}`);
if (trimmed === 'exit') {
console.log('Goodbye!');
process.exit(0);
}
});
Common Beginner Mistakes
1. Forgetting to Save the File
Always save before running node filename.js.
2. Wrong Directory
Make sure your terminal is in the same directory as your file:
cd /path/to/your/project
node app.js
3. Syntax Errors
Node.js will show you where errors occur:
SyntaxError: Unexpected token
at /path/to/file.js:5:10
4. Using Browser APIs
Remember, document, window, and alert don't exist in Node.js!
Key Takeaways
- Run Node.js files with
node filename.js - Use the REPL (
nodewith no arguments) for quick experiments process.argvcontains command line argumentsprocess.envcontains environment variablesprocess.exit(code)exits with a status code- Exit code 0 means success; non-zero means error
Summary
You've written and run your first Node.js programs! You've learned to use the REPL for experimentation, access command line arguments and environment variables, and build simple CLI tools. These fundamentals will serve as the foundation for everything else you'll learn in this course.
Next, you'll dive into the Node.js module system and learn how to organize your code into reusable pieces.

