node js

Body-parser is a middleware for Node.js that processes incoming HTTP requests. It extracts the request body and exposes it on the request object. This makes it easier to handle the request body, which can contain data such as form data, JSON, or file uploads.
Body-parser is often used to handle data sent in HTTP requests, such as form submissions or API requests. It allows you to access the data in your route handlers and use it to create or modify resources.

Blocking: It refers to the blocking of further operation until the current operation finishes. Blocking methods are executed synchronously. Synchronously means that the program is executed line by line. The program waits until the called function or the operation returns.

Non-Blocking: It refers to the program that does not block the execution of further operations. Non-Blocking methods are executed asynchronously. Asynchronously means that the program may not necessarily execute line by line. The program calls the function and move to the next operation and does not wait for it to return.

What is the control flow function?

The control flow function is a piece of code that runs in between several asynchronous function calls.

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
Control flow in Node. js is typically managed using one of three methods: callbacks, promises, and async/await. 1. Callbacks: Callbacks are functions that are passed as arguments to other functions and are executed when that function completes its task.


What is the control flow function in node js?
A control flow function is a lightweight, generic piece of code which runs in between several asynchronous function calls and which take care of the necessary housekeeping to: control the order of execution, collect data, limit concurrency and.

In computer programmingcontrol flow or flow of control is the order function callsinstructions, and statements are executed or evaluated when a program is running. Many programming languages have what are called control flow statements, which determine what section of code is run in a program at any time. An example of a control flow statement is an if/else statement, shown in the following JavaScript example.

var x = 1;
if (x === 1) {
window.alert("x is equal to 1.");
}
else {
window.alert("x is not equal to 1.");
}

In this example, if the variable x is set equal to 1, then the code in the curly brackets {} after the "if" statement is executed. Otherwise, the code in the curly brackets after the "else" statement is executed. This code works to control the flow of the program, depending on the value of the variable x.


what is the node js ?

 Node.js is an open-source server side JavaScript  runtime environment built on Chrome's V8 JavaScript engine

 It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime


  1. Single-threaded: In Node.js all requests are single-threaded and collected in an event loop. The event loop is what allows Node.js to perform all non-blocking operations. This means that everything from receiving the request to performing the tasks to sending the response to the client is executed in a single thread. This feature prevents reloading and reduces context switching time.

  2. Single-threaded: In Node.js all requests are single-threaded and collected in an event loop. The event loop is what allows Node.js to perform all non-blocking operations. This means that everything from receiving the request to performing the tasks to sending the response to the client is executed in a single thread.

    • Event Queue: All the requests sent by the clients are stored in the event queue. They are then passed one by one to the event loop. The callbacks of the operations running on other threads are also added to it so that the main thread takes them up.
    • Thread pool: Other than the main thread, there are other threads managed in a thread pool. All the asynchronous processes and non-blocking I/O are attached to one of these threads as they continue executing in the background.
    • External resources: These are the resources that the server has to fetch to fulfill client requests. They are needed to deal with the blocking requests. E.g., computation, data storage, etc.

    Workflow of Nodejs Server

    The workflow of a web server created with Node.js involves all the components discussed in the above section. The entire architectural work has been illustrated in the below diagram.

    Workflow of Nodejs Server

    • Clients send requests to the web server. These requests can be either blocking (complex) or non-blocking (simple). The purpose of the requests may be to query for data, delete data or update data.
    • The requests are retrieved and added to the event queue.
    • The requests are then passed from the event queue to the event loop one by one.
    • The simple requests are handled by the main thread, and the response is sent back to the client.
    • A complex request is assigned to a thread from the thread pool.
    • Clients send requests to the webserver to interact with the web application. Requests can be non-blocking or blocking:
    • Querying for data
    • Deleting data 
    • Updating the data
    • Node.js retrieves the incoming requests and adds those to the Event Queue
    • The requests are then passed one-by-one through the Event Loop. It checks if the requests are simple enough not to require any external resources
    • The Event Loop processes simple requests (non-blocking operations), such as I/O Polling, and returns the responses to the corresponding clients

    A single thread from the Thread Pool is assigned to a single complex request. This thread is responsible for completing a particular blocking request by accessing external resources, such as computation, database, file system, etc.

    Once the task is carried out completely, the response is sent to the Event Loop that sends that response back to the client.

REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL environment when it is installed. System interacts with the user through outputs of commands/expressions used. It is useful in writing and debugging the codes. The work of REPL can be understood from its full form:

Read : It reads the inputs from users and parses it into JavaScript data structure. It is then stored to memory.
Eval : The parsed JavaScript data structure is evaluated for the results.
Print : The result is printed after the evaluation.
Loop : Loops the input command. To come out of NODE REPL, press ctrl+c twice


Oh boi the event loop. It’s one of those things that every JavaScript developer has to deal with in one way or another, but it can be a bit confusing to understand at first. I’m a visual learner so I thought I’d try to help you by explaining it in a visual way through low-res gifs because it's 2019 and gifs are somehow still pixelated and blurry.

But first, what is the event loop and why should you care?

JavaScript is single-threaded: only one task can run at a time. Usually that’s no big deal, but now imagine you’re running a task which takes 30 seconds.. Ya.. During that task we’re waiting for 30 seconds before anything else can happen (JavaScript runs on the browser’s main thread by default, so the entire UI is stuck) 😬 It’s 2019, no one wants a slow, unresponsive website.

Luckily, the browser gives us some features that the JavaScript engine itself doesn’t provide: a Web API. This includes the DOM API, setTimeout, HTTP requests, and so on. This can help us create some async, non-blocking behavior 🚀

When we invoke a function, it gets added to something called the call stack. The call stack is part of the JS engine, this isn’t browser specific. It’s a stack, meaning that it’s first in, last out (think of a pile of pancakes). When a function returns a value, it gets popped off the stack 👋

The respond function returns a setTimeout function. The setTimeout is provided to us by the Web API: it lets us delay tasks without blocking the main thread. The callback function that we passed to the setTimeout function, the arrow function () => { return 'Hey' } gets added to the Web API. In the meantime, the setTimeout function and the respond function get popped off the stack, they both returned their values!

In the Web API, a timer runs for as long as the second argument we passed to it, 1000ms. The callback doesn’t immediately get added to the call stack, instead it’s passed to something called the queue.

This can be a confusing part: it doesn't mean that the callback function gets added to the callstack(thus returns a value) after 1000ms! It simply gets added to the queue after 1000ms. But it’s a queue, the function has got to wait for its turn!

Now this is the part we’ve all been waiting for… Time for the event loop to do its only task: connecting the queue with the call stack! If the call stack is empty, so if all previously invoked functions have returned their values and have been popped off the stack, the first item in the queue gets added to the call stack. In this case, no other functions were invoked, meaning that the call stack was empty by the time the callback function was the first item in the queue.

The callback is added to the call stack, gets invoked, and returns a value, and gets popped off the stack.


Reading an article is fun, but you'll only get entirely comfortable with this by actually working with it over and over. Try to figure out what gets logged to the console if we run the following:


const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");

bar();
foo();
baz();

Got it? Let's quickly take a look at what's happening when we're running this code in a browser:

  1. We invoke barbar returns a setTimeout function.
  2. The callback we passed to setTimeout gets added to the Web API, the setTimeout function and bar get popped off the callstack.
  3. The timer runs, in the meantime foo gets invoked and logs Firstfoo returns (undefined),baz gets invoked, and the callback gets added to the queue.
  4. baz logs Third. The event loop sees the callstack is empty after baz returned, after which the callback gets added to the call stack.
  5. The callback logs Second.

Hope that this makes you feel a bit more comfortable with the event loop! Don't worry if it still seems confusing, the most important thing is to understand where certain errors/behavior can come from in order to Google the right terms efficiently and end up on the correct Stack Overflow page 💪🏼 Feel free to reach out to me if you have any questions!

Comments