简体   繁体   中英

node.js: access exported function from other file

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!

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

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) {
  ..
  }

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(...);
     ..
  }
  ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM