Node.js REPL
Imagine you're learning a new language and you want to practice speaking immediately without writing a full essay. That's exactly what REPL does for Node.js – it's an interactive playground where you can type JavaScript and see results instantly!
What is REPL?
REPL stands for Read-Eval-Print Loop. It's an interactive programming environment that:
- Reads your input (JavaScript code).
- Evaluates (executes) it.
- Prints the result.
- Loops back to wait for more input.
Think of REPL as a conversation with Node.js. You say something (write code), and Node.js responds immediately (shows output).
Starting REPL
Open your terminal and simply type:
nodeYou'll see a `>` prompt. Now you're in REPL mode!
Basic REPL Commands
| Command | What It Does |
|---|---|
| `.help` | Shows all available REPL commands. |
| `.break` | Exit from multi-line input. |
| `.clear` | Clear the REPL context (reset variables). |
| `.save filename.js` | Save your REPL session to a file. |
| `.load filename.js` | Load a file into the REPL session. |
| `.exit` | Exit REPL (or press Ctrl+C twice). |
Using REPL for JavaScript Practice
Let's try some examples:
> 5 + 38> const name = 'Node.js';undefined> console.log(`Hello, ${name}!`);Hello, Node.js!undefined> const numbers = [1, 2, 3, 4];undefined> numbers.map(n => n * 2);[ 2, 4, 6, 8 ]Notice that when you assign a variable, it returns `undefined`. When you evaluate an expression, it returns the result.
Using Modules in REPL
You can also require and use modules in REPL:
> const fs = require('fs');undefined> fs.readdirSync('.');[ 'file1.txt', 'file2.js', 'folder' ]> const path = require('path');undefined> path.extname('image.jpg');'.jpg'Multi-line Code in REPL
You can write multi-line code by using curly braces `{}`. REPL will show `...` indicating it's waiting for more input:
> function greet(name) {... console.log(`Hello, ${name}!`);... }undefined> greet('Node');Hello, Node!Saving and Loading REPL Sessions
This is a powerful feature. You can save your entire REPL session to a file:
> const x = 100;> const y = 200;> function add(a, b) { return a + b; }> .save mysession.jsSession saved to: mysession.jsLater, you can load it back:
> .load mysession.jsTab Completion
REPL supports tab completion. Type part of a variable or function name and press `Tab` to see suggestions:
> cons <!-- Press Tab -->consoleWhen to Use REPL
- Learning JavaScript: Test syntax and features instantly.
- Debugging: Check values and test small code snippets.
- Exploring APIs: Try out built-in modules without creating files.
- Quick calculations: Use it as a calculator.
Two Minute Drill
- REPL = Read-Eval-Print Loop – an interactive JavaScript environment.
- Start REPL by typing `node` in terminal.
- Use `.help` to see available commands.
- Save sessions with `.save` and load with `.load`.
- Perfect for testing, learning, and debugging.
Need more clarification?
Drop us an email at career@quipoinfotech.com
