【发布时间】:2015-12-29 04:43:24
【问题描述】:
我遇到了 Node.js 和 module.exports 的问题。我知道module.exports 是一个返回对象的调用,该对象具有分配给它的任何属性。
如果我有这样的文件结构:
// formatting.js
function Format(text) {
this.text = text;
}
module.exports = Format;
用这个:
// index.js
var formatting = require('./formatting');
有没有办法初始化Format 对象并像这样使用它?
formatting('foo');
console.log(formatting.text);
每当我尝试这样做时,都会收到一条错误消息,显示为formatting is not a function。然后我必须这样做:
var x = new formatting('foo');
console.log(x.text);
这看起来很麻烦。
在keypress 和request 等模块中,它们可以直接使用,如下所示:
var keypress = require('keypress');
keypress(std.in);
或
var request = require('request);
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
这是如何工作的?
【问题讨论】:
-
这行得通吗? varformatting = require('./formatting.js');
-
在您的代码中,您从格式化模块返回函数构造函数。相反,您希望将其作为对象返回,以便您可以直接使用它。
-
@PardeepDhingra 我该怎么做?
-
@apizzimenti 检查我的答案。
标签: javascript node.js node-modules