在 Node.JS 中,如何从单独的.js文件中返回整个对象

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

本文关键字:文件 js 返回 对象 JS Node 单独      更新时间:2023-09-26

我是 Node 的新手.js并试图弄清楚如何从单独的文件中请求对象(而不仅仅是请求函数(,但我尝试的所有内容——exportsmodule-exports等——都失败了。

因此,例如,如果我有foo.js

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

现在我想从index.js调用foo.js对象中的函数:

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

我该怎么做? 我已经尝试了各种exportsmodule-exports的组合,但它们似乎只有在调用不属于对象的离散函数时才有效。

你说你试过exports,但你的代码没有显示它。您希望从模块外部可见的任何内容都必须分配给(或以其他方式引用(module.exports 。在您的情况下,如果您已经有一个对象,您可以将其分配给module.exports

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

module.exports不是魔法,它是一个普通的物体,你可以这样对待它。这意味着您可以将方法直接分配给它,如下所示:

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

或者,您可能知道,您可以用函数替换它:

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

只有在导出后,您才能使用其他模块中的任何内容