Reputation: 5467
I have the following code:
// jira.js
var exports = module.exports = {};
module.exports = function () {
var exported = {};
..
exported.myMethod= function (bugId, done) {
..
}
..
return exported;
};
and i want to use the myMthod function from other file bugs.js in the same directory:
var exports = module.exports = {};
var jira = require('./jira');
module.exports = function () {
var exported = {};
..
exported.secondMethod= function (bugId, done) {
jira.myMethod(...) {
}
..
}
..
return exported;
};
When i try to access myMthod from bugs.js, i get ' undefined'. Upon doing console.log(jira) jyst above the call to jira.myMthod() , i see the entire js file logged out.
How do i get this to work?
Please advise,
thanks!
Upvotes: 1
Views: 196
Reputation: 163
This simplifies down to setting your exported object to a variable and then setting module.exports equal to that var. Then on import, just require the file and use the imported file as if it is a normal object.
To export:
// jira.js
var jira = {};
...
jira.myMethod = function (bugId, done) {
...
}
...
module.exports = jira;
To access:
//bugs.js
var jira = require('./jira');
var bugs = {};
..
bugs.secondMethod= function (bugId, done) {
jira.myMethod(...);
..
}
..
Upvotes: 0
Reputation: 793
When you require a module, the result of require(...)
is whatever is assigned to module.exports
in that module. In this case you're assigning a function that returns an object with the methods you want.
So either use it as:
var jira = require('./jira')();
jira.myMethod();
or change the jira.js to something like:
var exports = module.exports = {};
exports.myMethod = function (bugId, done) {
..
}
Upvotes: 1
Reputation: 12953
since your module.exports in jira is a function, you need to execute it in order to get the returned value (you can do it by requiring it like this: var jira = require('./jira')();
which will return the exported functions).
But in my mind, this is redundant. I prefer this syntax:
// jira.js
function myMethod (bugId, done) {
..
}
..
return {
myMethod : myMethod
};
what this will make is when you require jira, it will run to code (in this case, define the function) and will return it
Upvotes: 1