# NodeJS

## Introduction

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2Fx653VS6eJgfE8gZOr0qH%2Fimage.png?alt=media\&token=d4d4d8ec-7c55-4760-a430-d0e69867d939)

* It provides javascript runtime environment which is similar with browsers
* It is used V8 Engine to execute javascript code

## Lifecycle & Event loop

```javascript
const http = require("http");

const server = http.createServer((req,res)=>{
    ...
});

server.listen(3000);
```

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FFkhfrsyZ1A5us7csA2jN%2Fimage.png?alt=media\&token=de48ffe7-0375-4491-8a98-71532c88efdd)

* The server which is also a event listener is registered, the event loop process keep on running and handle the callback function

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FtE1sSa50cVK39bPbv37M%2Fimage.png?alt=media\&token=19ee16f0-228b-4ce3-81ee-d2fb8064a2ad)

* As the javascript is single-thread, in order to make it non-blocking and handle multiple request efficiently, there is a event loop to handle the callback of event.
* Nodejs use event-driven programming . for each connection to the server, it is treated as an event and event handler as a callback function.
* E.g: Handling File I/O: the file system operation will be handled by worker pool which is responsible for heavy-lifting and detached from the javascript thread . When finished, the callback of function will be queued and then executed

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FDlMpCEWw1oIMohL4qW3c%2Fimage.png?alt=media\&token=55ba673c-b783-47a4-a919-e42c541493b0)

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2F33ZtocHBFRkmIMKdHZZ2%2Fimage.png?alt=media\&token=a7b1441b-8881-41e0-9dbc-2bca6e967950)

* There is sequence for queue of event loop
* nextTick queue is the highest, which is process.nextTick()
* jobTask queue follows to nextTick queue, which is the callback of promise
* task queue follows to the job queue
* Here is the example to show the sequence of the event loop tasks

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FQLG2Xy1Kpm1J47PQa4B9%2Fimage.png?alt=media\&token=aad2e976-9a9f-4537-93b4-4af5ea40c6aa)

* Here is the result

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FME1UHMqhjmRRVUcipls6%2Fimage.png?alt=media\&token=a92a6ea7-5bb3-4fb8-8816-7618983072b7)

## Reference

{% embed url="<https://www.bitovi.com/blog/5-reasons-to-choose-nodejs>" %}

{% embed url="<https://roadmap.sh/nodejs>" %}
