Running with
Node.js
Learn how to execute JavaScript outside the browser using Node.js and the node file.js command in your terminal.
What is Node.js?
JavaScript was originally built to run only inside web browsers. Node.js changed everything by providing a runtime environment that lets you execute JavaScript directly on your computer, without needing a browser at all.
Browser vs. Node.js
Why Run JS Outside the Browser?
Node.js opened the door for JavaScript to become a general-purpose programming language, not just a browser scripting tool.
The Core Command: node file.js
How node file.js Works
REPL vs. File Execution
| node (REPL) | node file.js | |
|---|---|---|
| How to start | Type node and press Enter | Type node app.js |
| Input | One line at a time, interactively | Entire file is read at once |
| Best for | Quick experiments, testing | Real programs, scripts, servers |
| Code saved? | Lost when you exit | Saved in a .js file permanently |
| Exits when | You type .exit or Ctrl+C | Code finishes running |
Running Your First Script
Example 1: Hello World
console.log("Hello, world!");
Hello, world!
Example 2: Variables and Logic
const radius = 5;
const area = Math.PI * radius * radius;
console.log("Area:", area.toFixed(2));
Area: 78.54
Example 3: Error Messages
let name = "Alice";
console.log(nmae); // typo!
ReferenceError: nmae is not defined
at Object.<anonymous> (broken.js:2:13)
File Paths Matter
console.log in Node.js
The same code, different destination. In Node.js, console.log() writes to stdout (standard output): your terminal screen. This is the primary way to see results from a Node.js script.
Passing Arguments to Scripts
const name = process.argv[2];
console.log("Hello, " + name + "!");
Hello, Alice!
Common Mistakes
Quick Reference Summary
| Command | What It Does | Example |
|---|---|---|
| node file.js | Run a JavaScript file | node app.js |
| node | Open interactive REPL | node then type code |
| node -v | Check installed version | v20.11.0 |
| node -e "code" | Run inline code | node -e "console.log(42)" |
| Ctrl + C | Stop a running script | Exit infinite loops |
Question 1 of 5
What does the node command do in node app.js?
Question 2 of 5
Where does console.log() output appear when you run a script with Node.js?
Question 3 of 5
You type node app.js and get the error "Cannot find module". What is the most likely cause?
Question 4 of 5
What is the difference between typing node alone and node file.js?
Question 5 of 5
In the array process.argv, what value is stored at index [2] when you run node greet.js Alice?