我遇到了一个关于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.
}
})
这是如何运作的呢?