Node.js Basics and First Program
# 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
letandconstproperly in a Node context.
-
Utilize advanced
console.logformatting 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 useconst and let to declare variables.
-
Use
constwhen a value will never change (like a server port or a configuration string).
-
Use
letwhen 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 usedconsole.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 likenode 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);
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});
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);
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
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!);
}
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. How do you read command line arguments in Node.js?
array. Indexes 0 and 1 represent the node executable and file path, so user arguments start at index 2.
-
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.
-
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.