What exactly is Node.js ?
If you know Java, here’s a little analogy.
I/O refers to input/output. It can be anything ranging from reading/writing local files to making an HTTP request to an API. I/O takes time and hence blocks other functions.
Consider a scenario where we request a backend database for the details of user1 and user2 and then print them on the screen/console. The response to this request takes time, but both of the user data requests can be carried out independently and at the same time.
Blocking I/O vs Non-Blocking I/O (right)
On the other hand, using a non-blocking request, you can initiate a data request for user2 without waiting for the response to the request for user1. You can initiate both requests in parallel. This non blocking I/O eliminates the need for multi-threading since the server can handle multiple requests at the same time.
- Push main() onto the call stack.
- Push console.log() this runs right way and gets popped.
- Push setTimeout(2000) is a Node API. When we call it, we register the event call pair back.
- After registering in API SetTimeOut(2000) gets popped from the call stack.
- Now the second setTimeOut(0) get registered in the same way.
- After waiting for 0 second setTimeOut(0) gets moved to the call back queue.
- The las console.log() runs and the main() gets popped from the call stack.
These are libraries built by the awesome community which will solve most of your generic problems. npm (Node package manager) has packages you can use in your apps to make your development faster and efficient.
Require does three things:
- It loads modules that come bundled with Node.js like file system and HTTP from the Node.js API .
- It loads third-party libraries like Express and Mongoose that you install from npm.
- It lets you require your own files and modularize the project.
Require is a function, and it accepts a parameter “path” and returns module.exports.
A Node module is a reusable block of code whose existence does not accidentally impact other code. You can write your own modules and use it in various application. Node.js has a set of built-in modules which you can use without any further installation.
Written by: Nabeel Leghari