REPL, Running Files & Watch Mode

Node.js · Lesson 3 of 30 8 min read Updated

There are two ways to run JavaScript with Node.js. You can type code line by line in an interactive prompt called the REPL, which is perfect for quick experiments. Or you can save code in a .js file and run the whole file, which is how real programs work.

In this lesson you will use both, run one-line commands from the terminal, read the error messages Node.js prints, and use watch mode so your program restarts by itself every time you save.

The REPL

REPL stands for Read, Evaluate, Print, Loop. It reads what you type, runs it, prints the result, and waits for the next line. Start it by typing node with nothing after it:

Terminal
node

You will see a > prompt. Type an expression and press Enter:

Text
Welcome to Node.js v26.13.0.
Type ".help" for more information.
> 2 + 3 * 4
14
> const fare = 1299
undefined
> fare * 2
2598
> _ + 1
2599
> "Lucknow".toUpperCase()
'LUCKNOW'
> [10, 20, 30].map((n) => n / 10)
[ 1, 2, 3 ]
> await Promise.resolve("done")
'done'
> path.extname("photo.jpg")
'.jpg'

A few things to notice:

  • The REPL prints the value of each expression. A declaration such as const fare = 1299 has no value, so it prints undefined. That is normal, not an error.
  • The special variable _ holds the last result.
  • Strings are shown in quotes and arrays with spaces, so you can see the exact type.
  • await works directly at the prompt, which is handy for testing promises.
  • Built-in modules such as path, fs and os are ready to use in the REPL without importing them. In a file you must import them.

Useful REPL commands

Commands that start with a dot control the REPL itself:

Command or keyWhat it does
.helpList all dot commands
.editorEnter editor mode to type many lines; finish with Ctrl+D
.save notes.jsSave everything you typed in this session to a file
.load notes.jsRun a file's code inside the REPL
.exit or Ctrl+DLeave the REPL
Ctrl+CCancel the current line; press twice to leave
TabComplete names, for example "abc".to then Tab
Up arrowBring back earlier lines

If you start a line such as function add(a, b) { and press Enter, the REPL shows ... and waits for the rest. Finish the code or type .break to give up on it.

Running a file

The REPL forgets everything when you leave. For real work, write a file. Create marks.js:

JavaScript
const marks = { maths: 88, science: 92, english: 79 };

const total = Object.values(marks).reduce((sum, m) => sum + m, 0);
const average = total / Object.keys(marks).length;

console.log(`Total: ${total}`);
console.log(`Average: ${average.toFixed(1)}`);
console.log(`Result: ${average >= 33 ? "Pass" : "Fail"}`);

Run it from the folder that contains it:

Terminal
node marks.js
Output
Total: 259
Average: 86.3
Result: Pass

Node.js runs the file from top to bottom. Then it checks the event loop: if there are no timers, open servers or other pending work, the program exits by itself. A web server never exits on its own because it keeps listening for requests. Press Ctrl+C to stop it.

One-line commands with -e and -p

For a tiny calculation you do not need a file. The -e (evaluate) option runs code, and -p (print) runs code and prints the result:

Terminal
node -p "21 * 2"
node -p "process.platform"
node -e "console.log(new Date(2026, 0, 26).toDateString())"
Output
42
win32
Mon Jan 26 2026

process.platform prints win32, darwin or linux depending on your system. Wrap the code in double quotes so the terminal passes it to Node.js as one piece.

Reading errors and stack traces

When your code throws an error that nothing catches, Node.js prints a report and stops with exit code 1 (a non-zero exit code means "something failed"). Here is a mistake every beginner makes:

JavaScript
const student = { name: "Rohan" };

function printCity(person) {
  console.log(person.address.city.toUpperCase());
}

printCity(student);
Output
C:\node-course\broken.js:4
  console.log(person.address.city.toUpperCase());
                             ^

TypeError: Cannot read properties of undefined (reading 'city')
    at printCity (C:\node-course\broken.js:4:30)
    at Object.<anonymous> (C:\node-course\broken.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1554:14)
    ...

Node.js v26.13.0

Read it from the top:

  1. The file and line number (broken.js:4) and a caret ^ that points at the exact spot.
  2. The error type and message. Here person.address is undefined, and you cannot read city from undefined.
  3. The stack trace: the chain of function calls that led to the error, newest first. printCity at line 4, called from line 7. Lines that start with node:internal are inside Node.js itself and you can usually ignore them.

The fix is to check the data, for example with optional chaining: person.address?.city ?? "City not given".

To check a file for syntax errors without running it, use node --check file.js. It prints nothing if the syntax is fine.

Watch mode: restart on every save

While you build a server you change the code again and again. Stopping it with Ctrl+C and starting it again each time is slow. Watch mode does it for you: Node.js watches your file and every file it imports, and restarts the program whenever one of them changes.

Terminal
node --watch price.js

Suppose price.js prints Price: 1299, and while it is being watched you change it to print the Diwali price and save. With --watch-preserve-output added so the old lines stay on screen, the terminal shows:

Output
Price: 1299
Completed running 'price.js'
Restarting 'price.js'
Price: 999 (Diwali sale)
Completed running 'price.js'

By default watch mode clears the terminal before each restart, which keeps it tidy. Press Ctrl+C to stop watching. Watch mode is stable since Node.js 22. Two related options:

  • --watch-path=./src watches a whole folder instead of the files you import (Windows and macOS only).
  • --watch-preserve-output keeps old output instead of clearing the screen.

Common mistakes

  • Typing node marks.js inside the REPL. The REPL expects JavaScript, so you get a SyntaxError. Leave the REPL with .exit and type the command in the normal terminal.
  • Running the command from the wrong folder. Error: Cannot find module 'C:\...\marks.js' usually means the file is in a different folder. Use cd to move to it first.
  • Thinking undefined in the REPL is an error. It only means the line had no value.
  • Using watch mode in production. It is a development tool. Production servers use a process manager, covered in Deployment.

Key points

  • Type node alone to start the REPL; it prints the value of each expression and _ holds the last result.
  • Dot commands such as .help, .editor and .exit control the REPL.
  • node file.js runs a file; the program exits when the event loop has nothing left to do.
  • node -p "expression" prints a result; node -e "code" runs code; node --check checks syntax only.
  • Read stack traces from the top: file and line, error message, then the chain of calls.
  • node --watch file.js restarts your program on every save, replacing nodemon for most projects.

Exercise

Write a file bill.js that stores three items from a stationery shop in an array of objects (name and price in rupees), prints each item on its own line and then prints the total. Run it with watch mode, then add a fourth item and save the file to see it restart. Finally, use node -p to work out 18% GST on ₹450 without creating a file.

Show solution
JavaScript
// bill.js
const items = [
  { name: "Notebook", price: 60 },
  { name: "Gel pen pack", price: 120 },
  { name: "Geometry box", price: 270 },
];

for (const item of items) {
  console.log(`${item.name}: ₹${item.price}`);
}

const total = items.reduce((sum, item) => sum + item.price, 0);
console.log(`Total: ₹${total}`);
Terminal
node --watch bill.js
node -p "450 * 0.18"
Output
Notebook: ₹60
Gel pen pack: ₹120
Geometry box: ₹270
Total: ₹450
Completed running 'bill.js'
81

--watch reruns bill.js every time you save it. The last line is the separate node -p command: 18% of ₹450 is ₹81.

Quick Quiz

1. What does the REPL print after const city = "Kochi"?

2. Which command prints the result of an expression without creating a file?

3. In a stack trace, which line usually points to your own mistake?

4. What does node --watch server.js do?

Learn Node.js with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call