You have used sum for your function; but I will be using divide, because that way I can show you the error thing of callback.
your export will look like this
module.exports = {
divide: (a,b,cb) => {
if (b === 0) {
cb('divide by zero', null);
} else {
cb(null, a/b);
}
}
}
and the import like this
var func = require('./testExport').divide;
func(1,2,(err,res) => {
console.log(err,res);
});
func(1,0,(err,res) => {
console.log(err,res);
})
Call backs are simply the function that you send in from the place you are calling the functions. In both function calls (in imported place) you see we are sending in a function as a callback that takes in two arguments.
In the exported place we call that same function with the first parameter as an error and the second as res.
If you want to import your function without require().func, you will have to export the function in default.
module.exports = (a,b,cb) => {
if (b === 0) {
cb('divide by zero', null);
} else {
cb(null, a/b);
}
}
and import it as
var defaultFunc = require('./testExport')