Reputation: 43
So, while I was using this require('fileName.js') to add an external JavaScript file to my main index.js file.
In the index.js
const caltor = require('./calculate.js');
console.log(caltor.adding(5,7));
In my calculate.js
function adding (i,y){
return i+y;
}
BTW I am using nodejs to execute.
The error says:
console.log(caltor.adding(5,7));
^
TypeError: caltor.adding is not a function
Upvotes: 1
Views: 391
Reputation: 18619
Node.js modules don't automatically export their top-level scope variables/functions.
To export a value, you have two ways:
Add it to the exports
object
Node modules have a predefined variable exports
, whose value is exported. Add your function to it:
function adding (i,y){
return i+y;
}
exports.adding = adding
const caltor = require('./calculate.js');
console.log(caltor.adding(5,7));
You can also export multiple values this way, just be sure to giv them a different name:
function adding (i,y){
return i+y;
}
exports.adding = adding
function subtracting (i,y){
return i-y;
}
exports.subtracting = subtracting
const caltor = require('./calculate.js');
console.log(caltor.adding(5,7));
console.log(caltor.subtracting(5,7));
Providing a "default" export by assigning to module.exports
If you want to export a single value, you can assign it to module.exports
. In this case, it becomes the value returned by require
.
Note that after assigning module.exports
, defining a property on the exports
variable will no longer work. Neither will assigning to exports
varible export anything.
function adding (i,y){
return i+y;
}
module.exports = adding
const adding = require('./calculate.js');
console.log(adding(5,7));
Upvotes: 2
Reputation: 326
You need to export the function 'adding' in your 'calculate.js' file.
module.exports = adding;
in your index.js file, no need to call caltor.adding() (Assuming that you only export one function from 'calculate.js').
console.log(caltor(5,7));
Upvotes: 3