Concept Explanation
Node.js is not a programming language; it's a Runtime that lets you run JavaScript on your computer (outside the browser).
The secret to Node's speed is Libuv. While JavaScript is single-threaded, Libuv allows Node to give heavy tasks (like reading a file or talking to a database) to the computer's Operating System. The OS does the work in the background, and Node just waits for the "Done!" signal. This is why a single Node.js server can handle thousands of users at once.
The Event Loop vs. Browser
In the browser, the event loop handles user clicks and animations. In Node, the event loop handles Incoming Requests and File Operations.
Best Practices
- Don't block the loop: Never run a massive mathematical calculation in the main Node thread. It will freeze the server for every user.
- Asynchronous is Default: Almost every Node function has an
Asyncversion (using Promises) and aSyncversion. Always use the Async version in a web server. - Use ESM: In modern Node (v18+), prefer
import/exportover the olderrequire().
Practice Exercises
- The Version Check: Run
node -vandnode -p "process.platform"in your terminal to see your environment details. - The Blocking Test: Write a script that runs a very long
forloop (10 billion times) and observe how the computer's CPU spikes. - Global Object: Compare the
windowobject in the browser to theglobalobject in Node. List three things that exist in Node but not in the browser.