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.
我是Node的新手。尝试从一个单独的文件中请求一个对象(而不是仅仅请求一个函数),但是我尝试的所有东西——导出、模块导出等等——都失败了。
So, for example, if I have foo.js
:
例如,如果我有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
:
现在我想调用foo对象中的函数。从index.js 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.
我该怎么做呢?我尝试过各种出口和模块出口的组合,但它们似乎只有在我调用一个不属于某个对象的离散函数时才有效。
1 个解决方案
#1
4
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
:
您说您尝试了导出,但是您的代码没有显示它。任何您希望在模块之外可见的内容都必须被分配到(或其他可引用的)modu .exports。在你的例子中,如果你已经有了一个对象,你可以把它分配给modu。export:
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.
只有导出之后,您才能在其他模块中使用任何内容。
#1
4
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
:
您说您尝试了导出,但是您的代码没有显示它。任何您希望在模块之外可见的内容都必须被分配到(或其他可引用的)modu .exports。在你的例子中,如果你已经有了一个对象,你可以把它分配给modu。export:
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.
只有导出之后,您才能在其他模块中使用任何内容。