Javascript Node.js“需要”函数和参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7367850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js "require" function and parameters
提问by user885355
When I do:
当我做:
lib = require('lib.js')(app)
is app
actually geting passed in?
在app
实际歌厅通过呢?
in lib.js:
在 lib.js 中:
exports = module.exports = function(app){}
Seems like no, since when I try to do more than just (app)
and instead do:
似乎没有,因为当我尝试做的不仅仅是做更多的(app)
事情时:
lib = require('lib.js')(app, param2)
And:
和:
exports = module.exports = function(app, param2){}
I don't get params2
.
我不明白params2
。
I've tried to debug by doing:
我尝试通过以下方式进行调试:
params = {}
params.app = app
params.param2 = "test"
lib = require("lib.js")(params)
but in lib.js when I try to JSON.stringify
I get this error:
但是在 lib.js 中,当我尝试时出现JSON.stringify
此错误:
"DEBUG: TypeError: Converting circular structure to JSON"
回答by Raynos
When you call lib = require("lib.js")(params)
你打电话时 lib = require("lib.js")(params)
You're actually calling lib.js
with one parameter containing two properties name app
and param2
您实际上是lib.js
使用一个包含两个属性名称app
和param2
You either want
你要么想要
// somefile
require("lib.js")(params);
// lib.js
module.exports = function(options) {
var app = options.app;
var param2 = options.param2;
};
or
或者
// somefile
require("lib.js")(app, param2)
// lib.js
module.exports = function(app, param2) { }
回答by Jim Schubert
You may have an undefined value that you're trying to pass in.
您可能有一个试图传入的未定义值。
Take for instance, requires.js
:
举个例子,requires.js
:
module.exports = exports = function() {
console.log('arguments: %j\n', arguments);
};
When you call it correctly, it works:
当您正确调用它时,它可以工作:
node
> var requires = require('./requires')(0,1,2,3,4,5);
arguments: {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5}
If you have a syntax error, it fails:
如果您有语法错误,则会失败:
> var requires = require('./requires')(0,);
... var requires = require('./requires')(0,2);
...
If you have an undefined object, it doesn't work:
如果你有一个未定义的对象,它不起作用:
> var requires = require('./requires')(0, undefined);
arguments: {"0":0}
So, I'd first check to see that your object is defined properly (and spelled properly when you pass it in), then check that you don't have syntax errors.
因此,我会首先检查您的对象是否正确定义(并在您传入时正确拼写),然后检查您是否没有语法错误。