Node.js is a JavaScript runtime environment that includes everything you need to execute a program written in JavaScript. It converts your JavaScript code into machine code and converts it into a faster machine code. Sounds great, but what does that mean? How does that work? The Node run-time environment includes everything
Why is Node.js so popular?
The JavaScript runtime built on Chrome’s V8 JavaScript engine
- Uses an event-driven, non-blocking I/O model that makes it lightweight and efficient
- Its package ecosystem, npm, is the largest ecosystem of open source libraries in the world
Blocking I/O
In the blocking method, user2’s data request is not initiated until user1’s data is printed to the screen.
V8 turbo-charges JavaScript by leveraging C++
V8 is an open source runtime engine written in C++ that can run standalone or embedded into any C++ application
- It has hooks that allow you to write your own C++ code that you can make available to JavaScript
- Let’s you add features to JavaScript
Non-blocking I/O
A non-blocking request allows you to initiate a data request for user2 without waiting for the response from user1.
Writing Hello World in Node.js
Make a file app.js.
- Add the following to it: console.log(“Hello World!”); Open your node terminal, change the directory to the folder where the file is saved, run node application.js and see the output.
The JavaScript event loop
Push main(), setTimeout(2000), and console.log() onto the call stack, then push setTimeout (2000) onto the stack.
- After waiting for a few seconds, main() gets popped and the next two functions get popped as well. The last function gets popped from the stack and the event loop takes over.
Require
Loads modules that come bundled with Node.js, and third-party libraries like Express and Mongoose that you install from npm