简体   繁体   中英

In Node.JS, how do I return an entire object from a separate .js file?

I am new to Node.js and trying to figure out how to request an object from a separate file (rather than just requesting a function) but everything I try-- exports , module-exports ,etc--is failing.

So, for example, if I have foo.js :

    var methods = {
                   Foobar:{
                            getFoo: function(){return "foo!!";},
                            getBar: function(){return "bar!!";}
                   }
                  };
module.exports = methods;

And now I want to call a function within an object of foo.js from index.js :

var m = require('./foo');  
function fooMain(){
  return m.Foobar.getFoo();
};

How do I do this? I have tried all sorts of combinations of exports and module-exports but they seem to only work if I call a discrete function that is not part of an object.

You said that you tried exports , but your code doesn't show it. Anything that you want to be visible from outside your module must be assigned to (or otherwise be referable from) module.exports . In your case, where you have an object already, you can just assign it to module.exports :

var methods = {
    ...
};

// You must export the methods explicitly
module.exports = methods;

module.exports isn't magic, it's a normal object, and you can treat it as such. Meaning that you could have assigned your methods directly to it, as in:

module.exports.Foobar = {};
module.exports.Foobar.getFoo = function() { ... };
...

Or, as you probably know, you could event replace it with a function:

module.exports = function() { return "It's ALWAYS over 9000!!!!"; };

Only after exporting will you be able to use anything in another module.

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