Node.js callbacks in exported modules

In this tutorial, we will see how to use callbacks in exported modules. This is a very important concept and one of its applications is error handling. We will be using an import and export module in Node.js. We need to make sure that type="module" is present in package.json to avoid any errors.

Callbacks in exported modules in Node.js

First, we will define the function that needs to be exported. Here functions add has three parameters. In the callback function, we will pass the sum and the error.


export function add(a, b, callback)  {
    let sum = a+b
      let error = null
      callback(error, sum) 


import { add } from "./calc.js";
add(1, 45, (err, result) => {
    if (err) {

Here we have imported the module. Here we are passing the error as the first parameter and the result as the second to the callback function. In case the error occurs null will be printed and if not then the result is printed.



Also read: How to Expire session after a specific time of inactivity in Express.js

Leave a Reply

Your email address will not be published. Required fields are marked *