我在使用 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
and request
,它们可以立即使用,如下所示:
var keypress = require('keypress');
keypress(std.in);
or
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.
}
})
这是如何运作的?