节点module.exports返回undefined
我有一个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. } })
这个怎么用?
我build议将new
调用包装在自己的函数中,然后返回:
function Format(text) { this.text = text; } function formatting(text) { return new Format(text); } module.exports = formatting;
这样你应该仍然可以做到:
var format = formatting('foo'); console.log(format.text);
编辑 :
就request
而言,你必须记住的一件事是,在JavaScript中,函数仍然是对象。 这意味着您仍然可以为它们添加属性和方法。 这就是他们request
做的事情,虽然总体来说这个答案中的每一个细节都有点复杂。 从我可以告诉的是,他们添加了一堆方法(对象上的函数)到request
函数。 这就是为什么你可以立即调用像request(blah, blah).pipe(blah).on(blah)
这样的方法。根据调用request
函数返回的内容,你可以链接其他一些方法。 当你使用请求时,它不是一个对象,它是一个函数(但在技术上还是一个对象)。 为了演示函数如何仍然是对象,以及如何向其中添加方法,请查看以下简单示例代码:
function hey(){ return; } hey.sayHello = function(name) { console.log('Hello ' + name); } hey.sayHello('John'); //=> Hello John
这基本上是他们正在做的事情,只是更复杂和更多的东西正在进行。
module.exports = Format;
这将返回Format
构造函数,当你require('./formatting')
另一方面,下面的代码将返回一个Format
的实例,您可以直接调用方法:
module.exports = new Format();
尝试这个:
模块格式:
function Format() { this.setter = function(text) { this.text = text; } this.show = function() { console.log(this.text); } } //this says I want to return empty object of Format type created by Format constructor. module.exports = new Format();
index.js
var formatting = require('./formatting'); formatting('Welcome'); console.log(formatting.show());