Node.js REPL Terminal - Interactive JavaScript Shell
The REPL (Read-Eval-Print Loop) is an interactive command-line tool that allows you to execute JavaScript code directly in the terminal. It's an excellent tool for learning Node.js, testing code snippets, and debugging applications.
What is REPL?
REPL stands for:
- Read: Reads user input
- Eval: Evaluates the input as JavaScript code
- Print: Prints the result
- Loop: Repeats the process
The REPL provides an interactive environment where you can:
- Execute JavaScript code line by line
- Test functions and expressions
- Explore Node.js modules
- Debug code interactively
- Learn JavaScript concepts
Starting the REPL
Basic REPL
To start the REPL, simply type node
in your terminal:
node
You'll see a prompt like this:
Welcome to Node.js v18.17.0.
Type ".help" for more information.
>
REPL with Options
You can start REPL with various options:
# Start REPL with strict mode
node --use-strict
# Start REPL with experimental features
node --experimental-modules
# Start REPL and load a file
node -i script.js
# Start REPL with specific version
node --version
Basic REPL Usage
Simple Expressions
> 2 + 3
5
> "Hello" + " " + "World"
'Hello World'
> Math.sqrt(16)
4
> new Date()
2024-12-25T10:30:45.123Z
Variables and Functions
> let name = "John"
undefined
> name
'John'
> function greet(name) {
... return `Hello, ${name}!`;
... }
undefined
> greet("Alice")
'Hello, Alice!'
> greet(name)
'Hello, John!'
Multi-line Input
For multi-line code, the REPL automatically detects incomplete statements:
> function calculate(a, b) {
... let sum = a + b;
... let product = a * b;
... return { sum, product };
... }
undefined
> calculate(5, 3)
{ sum: 8, product: 15 }
REPL Commands
Help Command
> .help
.break Sometimes you get stuck, this gets you out
.clear Alias for .break
.editor Enter editor mode
.exit Exit the repl
.help Print this help message
.load Load JS from a file into the REPL session
.save Save all evaluated commands in this REPL session to a file
Editor Mode
> .editor
// Entering editor mode (Ctrl+D to finish, Ctrl+C to cancel)
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Press Ctrl+D to execute
fibonacci(10)
55
Loading and Saving
// Save current session to a file
> .save session.js
Session saved to: session.js
// Load JavaScript from a file
> .load session.js
// File content will be executed
// Load and execute a file
> .load my-script.js
Clear and Break
// Clear the current multi-line expression
> function test() {
... .clear
>
// Break out of current input
> function test() {
... .break
>
Exit REPL
> .exit
// or
> process.exit()
// or press Ctrl+C twice
Advanced REPL Features
Working with Modules
// Load built-in modules
> const fs = require('fs')
undefined
> fs.readdirSync('.')
[ 'app.js', 'package.json', 'node_modules' ]
// Load custom modules
> const myModule = require('./my-module')
undefined
> myModule.someFunction()
'Hello from my module!'
Global Variables
// Access global variables
> global
[object global]
> process.version
'v18.17.0'
> process.platform
'linux'
> __dirname
'/home/user/projects'
> __filename
'/home/user/projects/repl-test.js'
Underscore Variable
The underscore (_
) variable contains the result of the last expression:
> 2 + 3
5
> _ * 2
10
> Math.sqrt(_)
3.1622776601683795
> _ + 1
4.1622776601683795
Error Handling
> throw new Error("Test error")
Error: Test error
at repl:1:7
at Script.runInThisContext (vm.js:96:20)
at REPLServer.defaultEval (repl.js:225:29)
at bound (domain.js:395:14)
at REPLServer.runBound [as eval] (domain.js:408:12)
at REPLServer.onLine (repl.js:443:10)
at emitOne (events.js:115:13)
at REPLServer.emit (events.js:210:7)
at REPLServer.Interface._onLine (readline.js:279:10)
at REPLServer.Interface._normalWrite (readline.js:424:12)
at Socket.ondata (readline.js:137:10)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:601:20)
Customizing REPL
Custom REPL Server
You can create a custom REPL server with specific options:
// custom-repl.js
const repl = require('repl');
// Create custom REPL server
const replServer = repl.start({
prompt: 'MyApp> ',
useColors: true,
useGlobal: true
});
// Add custom commands
replServer.defineCommand('hello', {
help: 'Say hello',
action(name) {
this.clearBufferedCommand();
console.log(`Hello, ${name || 'World'}!`);
this.displayPrompt();
}
});
// Add custom context
replServer.context.customVar = 'Custom Value';
// Handle exit
replServer.on('exit', () => {
console.log('Goodbye!');
process.exit();
});
Run the custom REPL:
node custom-repl.js
REPL with Custom Evaluation
// eval-repl.js
const repl = require('repl');
const replServer = repl.start({
eval: (cmd, context, filename, callback) => {
// Custom evaluation logic
try {
const result = eval(cmd);
callback(null, result);
} catch (error) {
callback(error);
}
}
});
// Add custom functions to context
replServer.context.add = (a, b) => a + b;
replServer.context.multiply = (a, b) => a * b;
Practical REPL Examples
Testing API Calls
> const https = require('https')
undefined
> function makeRequest(url) {
... return new Promise((resolve, reject) => {
... https.get(url, (res) => {
... let data = '';
... res.on('data', chunk => data += chunk);
... res.on('end', () => resolve(JSON.parse(data)));
... }).on('error', reject);
... });
... }
undefined
> makeRequest('https://api.github.com/users/octocat')
Promise { <pending> }
> // Wait for the promise to resolve
> const user = await makeRequest('https://api.github.com/users/octocat')
undefined
> user.login
'octocat'
Database Testing
> const mysql = require('mysql2/promise')
undefined
> const connection = await mysql.createConnection({
... host: 'localhost',
... user: 'root',
... password: 'password',
... database: 'test'
... })
undefined
> const [rows] = await connection.execute('SELECT * FROM users LIMIT 5')
undefined
> rows
[
{ id: 1, name: 'John', email: '[email protected]' },
{ id: 2, name: 'Jane', email: '[email protected]' }
]
File System Operations
> const fs = require('fs').promises
undefined
> const files = await fs.readdir('.')
undefined
> files
[ 'app.js', 'package.json', 'node_modules' ]
> const stats = await fs.stat('package.json')
undefined
> stats.size
245
> stats.isFile()
true
REPL Best Practices
1. Use for Learning and Testing
// Test new JavaScript features
> const obj = { a: 1, b: 2, c: 3 }
undefined
> Object.entries(obj)
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
> Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * 2]))
{ a: 2, b: 4, c: 6 }
2. Debug Complex Objects
> const complexObj = {
... users: [
... { id: 1, name: 'John', posts: [{ title: 'Post 1' }, { title: 'Post 2' }] },
... { id: 2, name: 'Jane', posts: [{ title: 'Post 3' }] }
... ],
... metadata: { total: 2, lastUpdated: new Date() }
... }
undefined
> complexObj.users[0].posts.length
2
> complexObj.users.map(user => user.name)
[ 'John', 'Jane' ]
3. Test Regular Expressions
> const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
undefined
> emailRegex.test('[email protected]')
true
> emailRegex.test('invalid-email')
false
> '[email protected]'.match(emailRegex)
[ '[email protected]', index: 0, input: '[email protected]', groups: undefined ]
4. Experiment with Async/Await
> async function delay(ms) {
... return new Promise(resolve => setTimeout(resolve, ms));
... }
undefined
> await delay(1000)
undefined
> console.log('This runs after 1 second')
This runs after 1 second
undefined
REPL Shortcuts
Keyboard Shortcuts
- Ctrl+C: Cancel current input
- Ctrl+D: Exit REPL
- Ctrl+L: Clear screen
- Up/Down Arrow: Navigate command history
- Tab: Auto-complete
- Ctrl+R: Search command history
Auto-completion
> process.
process.arch process.argv process.chdir
process.cwd process.env process.exit
process.nextTick process.platform process.version
// ... and many more
Troubleshooting REPL Issues
Common Problems
-
Stuck in Multi-line Mode
> function test() {
... // Press Ctrl+C to break out -
Memory Issues
> // Clear large variables
> largeArray = null
> // Force garbage collection (if available)
> global.gc && global.gc() -
Module Loading Issues
> // Clear module cache
> delete require.cache[require.resolve('./my-module')]
> const myModule = require('./my-module')
Integration with Development Tools
VS Code Integration
You can use REPL in VS Code's integrated terminal:
- Open VS Code
- Open integrated terminal (Ctrl+`)
- Type
node
to start REPL - Use VS Code's IntelliSense for auto-completion
Node.js Inspector
# Start REPL with inspector
node --inspect
# In another terminal, connect with Chrome DevTools
# Open chrome://inspect in Chrome browser
Next Steps
Now that you've mastered the REPL, you're ready to:
- Node.js - Command Line Options - Learn CLI parameters
- Node.js - Package Manager (NPM) - Learn package management
- Node.js - Callbacks Concept - Understand callback functions
- Node.js - Events - Learn event-driven programming
REPL Mastery Complete! You now know how to use the Node.js REPL effectively for learning, testing, and debugging. The REPL is an invaluable tool for any Node.js developer!