i

Node.js Callback Concept

Node.js is an event-driven javascript runtime environment. It is basically designed keeping scalability in mind. For a Node.js application, many concurrent users can create connections, and application can handle those concurrently.

After each connection, a callback is executed.

Callback is an asynchronous function and is called back at the completion of a task. All Node APIs are written in such a way so that They support callback.

A callback is a function that is to be executed after another function has finished executing — hence the name ‘call back’.

Most of frameworks and languages support common concurrency model. For every incoming request, they spawn a new thread, and each thread serves a unique request. The multithreading approach is inefficient and is difficult to use.

Why do we need Callbacks?

JavaScript is an event-driven language.

This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events.

Node.js uses Event loop as a runtime constructs instead of a library like many others. Node.js starts executing the next event after executing the input script, and there is no blocking to start the event loop.

fs.writeFile("./demo.txt","Fs Module and fs.writeFile method",()=>{

  console.log("Writing to the file demo.txt completed");

})

In the above example, we are trying to write “Fs Module and fs.writeFile method” content to demo.txt file kept in the same directory.

Meanwhile, content is being written to demo.txt; we might want the processor to perform some other tasks so control moves to the next statement in code.

Once the content is written to file, we might want to give the user notification or might want other functionality to initiate. So, we use the callback function.