All you need to understand Nodejs

Tram Ho

I’m TUAN, currently a Full-stack Developer in Tokyo.

If you find this Blog interesting, please give me a like and subscribe to support me.

You may have read these sentences before…

Node.js is a runtime to run JavaScript code built on Chrome’s JavaScript Engine V8

Node.js uses I/O model for event-driven, asynchronous Non-blocking

Node.js operates on a single thread event loop

…And you wonder what all this means. Hopefully by the end of this article you will have a better understanding of these terms and what Node is, how it works, why and when to use it.

Let’s start by going over the terms.

GET GO

I/O (Iput/Output)

Acronym for Input/Output, I/O mainly refers to the program’s interaction with the system’s drive and network. Examples of I/O operations include reading/writing drive data, making HTTP requests, and communicating with the database. They are very slow compared to accessing memory (RAM) or performing some logic on the CPU.

Synchronous vs Asynchronous

Synchronous (or sync – Synchronous) usually refers to code that executes in sequence. In synchronous programming, the program is executed line by line, line by line. Every time a function is called, program execution will wait until that function returns before continuing to the next line of code.

Asynchronous (or async – Asynchronous) refers to execution that does not run in the order that it appears in the code. In asynchronous programming, the program does not wait for the task to complete and can move on to the next task.

In the following example, synchronous processing causes the alert to fire in sequence. In an asynchronous operation, while alert(2) appears to execute a second time, it does not.

Asynchronous operations usually involve I/O, although setTimeout is an example of something other than I /O but still asynchronous. In general, anything involving computation is synchronous and anything involving input/output/time is asynchronous. The reason I/O operations are executed asynchronously is that they are very slow and it can potentially block the entire back-end processing.

Blocking vs Non-blocking

Blocking refers to operations that block execution until the operation is finished while Non-blocking refers to code that will not block execution. Or as the Node.js docs explain, Blocking is when JavaScript execution must wait until a non-JavaScript operation completes.

Blocking functions execute synchronously while Non-blocking functions execute asynchronously.

In the first example above, console.log would be called before moreWork(). In the second example fs.readFile() is Non-blocking so JavaScript execution can continue and moreWork()</ code>will be called first.

In Node, Non-blocking mainly refers to I/O operations. Remaining poor performance due to more CPU usage but not operations like “waiting for a non-JavaScript operation such as I/O” will not be called Blocking. (It’s simply because your logic is slow )

All I/O functions in the Node.js standard library provide asynchronous, Non-blocking versions and accept callback functions. Some functions can also be Blocking and often have names ending with Sync.

The Non-blocking I/O operations allow a single process to serve multiple requests at the same time. Instead of the program being Blocked and waiting for the I/O operations to complete. I/O operations are delegated to the system so that the program can execute the next piece of code. The Non-blocking I/O operation provides a function callback that is called when the operation completes.

Callback

Callback is a function that is passed as an argument to another function, which can then be called (callback) inside an action. motion immobilizer or other function. The call can be immediate (callback synchronous) or it can happen later (callback asynchronous).</p >

In the first example, the callback function is called inside the outer greetings function and writes to Terminal before moreWork() continues.

In the second example, fs.readFile (a function asynchronous do Node) provides) reads the file and when it finishes it calls the function callback which returns an error or file content. In the meantime, the program can continue to execute other processing.

A callback asynchronous can be called when an event occurs or when a task completes. It prevents Blocking by allowing other code to be executed in the meantime.

Instead of reading code from top to bottom in a procedural direction, the the asynchronous program may execute different function at different times based on the order and speed at which the function function previously requested http or read file from a file on the system. They are used when you don’t know when some asynchronous operation will complete.

You should avoid ” Callback hell “, situations where callback is nested within callback directives and so on, making code difficult understand, difficult maintenance and debug.

Events and Event-driven programming

Events are user- or system-generated actions, such as a click, a completed file download, or a hardware or software failure.< /p>

Event-driven programming is a programming model in which the flow of a program is determined by events. An event-driven programming performs actions in response to events. When an event occurs, it fires a function callback.

Now, let’s try to understand Node and see how all this related to it will work.

Node.js: what is it, why is it created and how does it work?

Simply put, Node.js is a platform that executes JavaScript programs that can communicate with other JavaScript programs. source I/O such as HTTP or system files etc

When Ryan Dahl created Node in 2009, he argued that

code class=”notranslate”>I/O is being processed incorrectly, Blocking the whole process is programmatically synchronous.

Traditional web serving techniques use a threading model, that is, one thread per request. Since in a I/O operation, the request spends most of the time waiting for it to complete, I/O</ scripts code> intensive requires a large amount of unused resources (such as memory) associated with these threads. Therefore, the "one thread per request" model for a single server is not good for scaling.

Dahl argues that software must be able to multi-task and proposes to eliminate waiting times for I/O return results. Instead of threading model, Dahl came up with a suitable way to handle several concurrent connections single-thread, event loop</ code> and Non-blocking I/O. For example, when you make a query to the database, instead of waiting for a response, you callback to it so your execution can run through the statement that and keep doing other things. When the result returns, it will call that callback function.

< strong>Event loop is what allows Node.js to perform I/O Non-blocking operations despite the fact that JavaScript is single- thread. A loop, running on the same thread as the JavaScript code, takes a task from the code and executes it. If the asynchronous task or I/O operation, the loop will push it down to the system kernel (system kernel), as is the case for new connections to the server or thread pool (multiple threads), such as file system related operations. Then the loop takes the next task and executes it.

Since most modern system kernel are multithreaded, they can handle a lot of background execution. When one of these operations completes (which is an event), system kernel will notify Node.js to call the command. The appropriate callback (depending on operation completion) can be added to the polling queue so that when the Stack is empty, it will execute it at last.

Node keeps track of asynchronous operations that haven’t completed, and event loop keeps repeating to check if they did. unfinished until all of them are done.

Unicorn Velociraptor library provides support for asynchronous based event loop

To match event loop single-thread, Node.js</ code> library using libuv to handle the execution of several I/O asynchronous Non-blocking operations in parallel. Main thread calling functions load tasks onto the task queue, threads in thread pool will pull back and execute incrementally.

Non-blocking main thread functions will run normally, while inherent Blocking functions like I/O will run Blocking on their own threads supported by system kernel. When a thread in thread pool completes a task, it notifies the main thread of this, and it calls callback</ code> has been passed in before.

1 * pIEFRBvMqxpDipMnqkVprA

Refer to Philip Roberts at JSConf EU: What the hell is event loop?

The image above is taken from Philip Roberts’ presentation at JSConf EU: Event loop is what what the heck? I recommend watching the whole video to get an idea of ​​how event loop.

Diagram explaining how event loop works with the browser but it looks essentially the same for Node. Instead of web APIs, we will have Node.

APIs

According to presentation, call Stack (aka stack executable or “Stack”) is a construct The data structure records our position in the program. When we execute a function, we put something on call Stack. If we return from a function, we take it out of the top call Stack.

This is how the code in the diagram is handled when we run it:

  1. Push main() to call Stack
  2. Push console.log('Hi'); to call Stack, execute immediately write “’Hi ‘” into Terminal and removed from call Stack
  3. Push setTimeout(cb, 5000) to call Stack. setTimeout is an API provided by the browser (on the back-end it would be a Node API). When setTimeout is called with the function callback and a delay argument, the handler browser will start the timer Timer with the time delay
  4. setTimeout called completed and removed from call Stack
  5. Push console.log('JSConfEU'); to call Stack, execute immediately write “JSConfEU” into Terminal and removed from call Stack
  6. main() removed from call Stack
  7. After 5000 milliseconds, the API timer completes and the callback command is moved to the task queue
  8. Event loop checks if call Stack is empty because JavaScript</code > is single-thread and can only do one thing at a time. If call Stack is empty, it will take the first Item (probably callback) on the queue and push it to call Stack. Thus, the loop pushes the callback command to call Stack
  9. The callback command is executed, writing “there” to the Terminal and removed from call Stack. And we’re done.

If you want to go into more detail on how Node.js, libuv, event loop and thread pool work, I suggest you take a look at the this, this and this along with Node docs.

1 * GYkdiL25aLDgkSW0phpAag

Node.js: Where and why to use it?

Since there is almost no Function in Node that directly implements I/ O, this process never Blocking, making it a good choice for developing highly scalable systems.</ p>

Do Event loop event-driven, single-threaded and paradigm I/O Non-blocking Asynchronous, Node.js works best on intense I/O applications require speed and scalability with multiple simultaneous connections, such as video and audio streaming, real-time applications, live chat, game applications, collaboration tools, or certificate exchange software. stock.

Node.js may not be the right choice for CPU intensive operations. The traditional threading model might work better instead.

npm

1 * Qj1OTPHk-djj2C1Nnkn4VQ

npm is the default package manager for Node.js and it is installed into the system when Node.js is installed. It can manage a specific project’s local dependencies, as well as globally installed JavaScript engines.

www.npmjs.com hosts thousands of free libraries to download and use in the program to help you grow faster and more efficiently. However, since anyone can create a library and there is no moderation process for submission, you must beware of low-quality, unsafe, or malicious libraries. npm relies on user reports to remove packages if they violate policies, and to help you decide, it includes statistics like downloads down and the number of packages depends.

How to run code in Node.js

Bắt đầu bằng cách cài đặt Node trên máy tính của bạn nếu bạn chưa có. Cách dễ nhất là truy cập nodejs.org và nhấp để tải xuống. Trừ khi bạn muốn hoặc cần có quyền truy cập vào các tính năng mới nhất, hãy tải xuống phiên bản LTS (Hỗ trợ dài hạn) cho hệ điều hành của bạn.

Chạy một ứng dụng Node từ Terminal của máy tính bằng cách: tạo một tệp “app.js” và thêm console.log(‘Hi’); vào tệp đó. Trên Terminal của bạn, hãy thay đổi thư mục thành thư mục chứa tệp đó bằng cách cd /path/... và chạy node app.js. Nó sẽ ghi “Hi” vào Terminal.

Như mọi khi, mình hy vọng bạn thích bài viết này và biết thêm được điều gì đó mới.

Cảm ơn và hẹn gặp lại các bạn trong những bài viết tiếp theo!

Nếu bạn thấy Blog này hay xin hãy cho mình một like và đăng ký để ủng hộ mình nhé. Thank you.

Ref

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo