REPL & running scripts
REPL and Running Scripts
1. REPL (Read-Eval-Print Loop)
The REPL is an interactive shell that processes JavaScript expressions in real-time. It’s like a sandbox for testing small snippets of code without creating a file.
How to access: Simply type
nodein your terminal and hit Enter.The Four Stages:
Read: Takes user input and parses it into JavaScript data structures.
Eval: Evaluates the data structure (executes the code).
Print: Prints the result to the console.
Loop: Loops back to the start, waiting for new input.
Pro-Tip: In the REPL, the underscore
_variable holds the result of the last evaluated expression. This is great for quick math or string manipulation!
2. Running Node.js Scripts
While REPL is for testing, real-world applications are written in
.jsfiles and executed via the terminal.
The Basic Command
To run a file, use the
nodecommand followed by the filename
node app.js
Execution Workflow
When you run a script, Node.js:
Starts the V8 Engine: Converts your JS into machine code.
Initializes the Event Loop: Prepares to handle asynchronous tasks (like database queries or API calls).
Executes the Script: Runs the code from top to bottom.
3. Automating with
package.jsonIn a professional MERN stack project, developers rarely type
node app.jsmanually. Instead, they use npm scripts.
Why? It allows you to chain commands (like setting environment variables or starting a debugger).
The "scripts" section:
"scripts": { "start": "node index.js", "dev": "nodemon index.js" }
Running it: You simply type
npm startornpm run dev.4. Development Tools (Nodemon)
Manually restarting the server every time you save a file is slow.
Nodemon is a utility that monitors your source code. When a change is detected, it automatically restarts the node application.
Command:
npx nodemon app.js(or defined in your npm scripts).