Skip to main content
Node.js Basics
CHAPTER 03 Beginner

Node.js Basics and First Program

Updated: May 13, 2026
15 min read

# Node.js Basics and First Program

Welcome to Chapter 3! Now that your environment is ready, it's time to write some real code. Because Node.js is essentially JavaScript, everything you know about basic JS applies here. However, interacting with the terminal is different than interacting with a web browser. In this chapter, we will cover variables, output formatting, capturing user input from the terminal, and build an interactive Command Line Interface (CLI) app.

---

1. Introduction

When you write JavaScript for the browser, your main goal is usually manipulating the DOM (HTML elements) or listening for user clicks.

In Node.js, your primary interface is the terminal/console. A backend program typically runs in the background, processes data, reads files, or talks to databases. We need to know how to effectively log information to the console to monitor our app and how to pass arguments into our scripts.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use let and const properly in a Node context.
  • Utilize advanced console.log formatting features.
  • Understand how to pass arguments to a Node.js script.
  • Read arguments using process.argv.
  • Create a basic interactive Command Line Application.

---

3. Beginner-Friendly Explanations

Variables Refresher

In modern JavaScript (and therefore Node.js), we use const and let to declare variables.
  • Use const when a value will never change (like a server port or a configuration string).
  • Use let when a value will change (like a counter or a user's score).
  • *Avoid using var*, as it's outdated and can cause scoping bugs.

Advanced Console Output

You've used console.log(), but the console object in Node.js has other helpful methods:
  • console.error(): Used to log error messages (often highlighted in red in some terminals).
  • console.table(): Great for displaying arrays or objects in a neat tabular format.
  • console.time() & console.timeEnd(): Used to measure how long a piece of code takes to run.

Understanding Command Line Arguments

When you run a command like node app.js, what if you wanted to pass data to the file, like node app.js John?

Node.js stores everything you type in the command line inside an array called process.argv (Argument Vector). By reading this array, your script can react differently based on user input.

---

4. Syntax Explanation

Let's look at how process.argv works.

```javascript id="ch3-syntax-1" // process.argv is a global array built into Node.js console.log(process.argv);

12345678910111213141516171819202122232425
If you run `node app.js hello world` in the terminal, the output will be an array with 4 items:
1. The absolute path to the Node.exe application.
2. The absolute path to your `app.js` file.
3. `"hello"`
4. `"world"`

To grab the actual words you typed ("hello" and "world"), you always look at index `2` and beyond.

---

## 5. Real-world Examples

### Why do we need Command Line Arguments?
Many development tools are built with Node.js. When you type commands like:
- `npm install express`
- `git commit -m "update"`

These are CLI programs reading your arguments (`install`, `express`, `commit`) and executing logic based on them. We are learning how to build the exact same type of tools!

---

## 6. Multiple Code Examples

### Example 1: Variables and Data Types

javascript id="ch3-code-1" const appName = "Backend Server"; // String let isActive = true; // Boolean const port = 3000; // Number

const serverConfig = { // Object host: "localhost", secure: false };

console.log(${appName} is running on port ${port}. Status: ${isActive});

1234
### Example 2: Using console.table

When working with databases, you often deal with arrays of users. `console.table` makes debugging incredibly easy.

javascript id="ch3-code-2" const users = [ { id: 1, name: "Alice", role: "Admin" }, { id: 2, name: "Bob", role: "User" }, { id: 3, name: "Charlie", role: "User" } ];

// This will print a beautiful table in your terminal console.table(users);

12
### Example 3: Performance profiling

javascript id="ch3-code-3" console.time("LoopTime"); // Start timer

let total = 0; for(let i = 0; i < 1000000; i++) { total += i; }

console.timeEnd("LoopTime"); // End timer and print result // Output: LoopTime: 2.345ms

1234
### Example 4: Capturing CLI Arguments

Create a file named `greet.js`:

javascript id="ch3-code-4" // greet.js // We get the 3rd item in the array (index 2) const userName = process.argv[2];

if (!userName) { console.error("Error: Please provide a name!"); console.log("Usage: node greet.js <your_name>"); } else { console.log(Hello, ${userName}! Welcome to Node.js!); }

1234567891011121314151617181920212223242526272829303132333435363738394041424344
Run in terminal:
`node greet.js Sarah` -> Output: `Hello, Sarah! Welcome to Node.js!`
`node greet.js` -> Output: `Error: Please provide a name!`

---

## 7. Output Explanations

When dealing with `process.argv`, understanding the zero-indexed array is crucial:
- `process.argv[0]` = The path to the Node executable (`C:\Program Files\nodejs\node.exe`).
- `process.argv[1]` = The path to your script (`C:\projects\greet.js`).
- `process.argv[2]` = The first argument you typed.
- `process.argv[3]` = The second argument you typed.

---

## 8. Common Mistakes

1. **Forgetting process.argv index offset:** Beginners often write `process.argv[0]` expecting to get their first argument, but they get the path to node.exe instead. Always start at index `2`.
2. **Treating arguments as Numbers:** Everything inside `process.argv` is a **String**. If you run `node calc.js 5 10`, `process.argv[2]` is `"5"`, not `5`. You must convert it using `parseInt()` or `Number()`.
3. **Multi-word arguments:** If you run `node greet.js John Doe`, Node sees "John" as index 2 and "Doe" as index 3. To pass them as a single string, wrap them in quotes: `node greet.js "John Doe"`.

---

## 9. Best Practices

- **Validate Input:** Never trust user input. Always check if the argument exists before trying to use it (as seen in Example 4).
- **Use Template Literals:** Use backticks `` ` `` and `${variable}` for string concatenation instead of the old `+` operator. It makes console output much cleaner.
- **Log Errors Clearly:** Use `console.error()` for failures so they stand out from standard `console.log()` messages.

---

## 10. Exercises

1. Create a script named `info.js`. Write an object containing details about a car (make, model, year) and use `console.table()` to display it.
2. Create a script named `multiply.js`. It should take two arguments from the command line, multiply them, and print the result. Remember to convert the strings to numbers!

---

## 11. Mini Project: CLI greeting app

**Objective:** Build a simple calculator CLI that takes an operation and two numbers.

**Code (`calc.js`):**

javascript id="ch3-mini-project" // calc.js const operation = process.argv[2]; const num1 = Number(process.argv[3]); const num2 = Number(process.argv[4]);

if (!operation || isNaN(num1) || isNaN(num2)) { console.error("Error: Invalid input."); console.log("Usage: node calc.js [add|sub|mult] [number1] [number2]"); process.exit(1); // Stop execution }

let result = 0;

if (operation === "add") { result = num1 + num2; } else if (operation === "sub") { result = num1 - num2; } else if (operation === "mult") { result = num1 * num2; } else { console.error("Unknown operation. Use add, sub, or mult."); process.exit(1); }

console.log(Calculating: ${num1} ${operation} ${num2}); console.log(Result: ${result}); ``

Run it: node calc.js add 10 25 -> Result: 35 node calc.js mult 5 5 -> Result: 25

---

12. Coding Challenges

Challenge 1: Enhance the calc.js project to also support division (div). Handle the edge case where a user tries to divide by zero!

Challenge 2: Write a script that checks if an inputted word is a palindrome. E.g., node palindrome.js racecar should output True.

---

13. MCQs with Answers

Q1: What does process.argv[2] represent? A) The path to Node.js B) The path to your file C) The first command line argument provided by the user D) The number of arguments passed Answer: C

Q2: Which method is best for displaying an array of objects in the terminal? A) console.log() B) console.dir() C) console.table() D) console.array() Answer: C

Q3: Command line arguments from process.argv are always formatted as: A) Numbers B) Objects C) Strings D) Booleans Answer: C

Q4: How do you stop a Node.js script manually inside the code? A) stop() B) break; C) process.exit() D) return; (at the global level) Answer: C

---

14. Interview Questions

  1. 1. How do you read command line arguments in Node.js?
*Answer:* You use the global
process.argv array. Indexes 0 and 1 represent the node executable and file path, so user arguments start at index 2.
  1. 2. What is the difference between let and const?
*Answer:* Both are block-scoped variable declarations. const creates a read-only reference to a value (it cannot be reassigned), while let allows the variable to be reassigned later.
  1. 3. If you pass the number 5 as an argument (node app.js 5), what data type is it inside process.argv?
*Answer:* It is a String ("5"). It must be parsed into a Number before performing mathematical operations.

---

15. FAQs

Q: Why do we use Number() instead of parseInt()? A: Both work! Number() is slightly stricter and converts the whole string into a float/integer, while parseInt() parses up to the first non-numeric character. For simple calculators, Number() is safer.

Q: Can I use prompts like in the browser (prompt('Enter name:'))? A: No, prompt() is a browser Window method. To get interactive, typing input *after* the script starts running, you have to use special Node modules like readline, which we will explore in later advanced topics.

---

16. Summary

  • const and let are the modern standards for declaring variables.
  • The console object has powerful tools like .table() and .time() for debugging and profiling.
  • Node.js captures all terminal commands in the process.argv array.
  • User-provided arguments start at index 2 and are always Strings.
  • You can forcefully stop a Node application using process.exit()`.

---

17. Next Chapter Recommendation

Writing all your code in one massive file is a terrible practice. In the professional world, code is split into dozens or hundreds of files! In Chapter 4: Node.js Modules, you will learn how to break your code into manageable pieces, export functions, and require them in other files to build modular, scalable applications.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·