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 node in your terminal and hit Enter.

  • The Four Stages:

    1. Read: Takes user input and parses it into JavaScript data structures.

    2. Eval: Evaluates the data structure (executes the code).

    3. Print: Prints the result to the console.

    4. 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 .js files and executed via the terminal.


The Basic Command

To run a file, use the node command followed by the filename


node app.js


Execution Workflow


When you run a script, Node.js:

  1. Starts the V8 Engine: Converts your JS into machine code.

  2. Initializes the Event Loop: Prepares to handle asynchronous tasks (like database queries or API calls).

  3. Executes the Script: Runs the code from top to bottom.


3. Automating with package.json


In a professional MERN stack project, developers rarely type node app.js manually. 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 start or npm 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).