节点module.exports返回undefined

Node module.exports returns undefined

本文关键字:undefined 返回 exports module 节点      更新时间:2023-09-26

我对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);

这看起来很麻烦。

在像keypressrequest这样的模块中,它们可以直接使用,如下所示:

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.
  }
})

这是怎么回事?

我建议将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函数返回的内容,你可以在它的后面链接一些其他方法。当你使用request时,它不是一个对象,而是一个函数(但从技术上讲,它仍然是一个对象)。要演示函数如何仍然是对象,以及如何向它们添加方法,请查看以下简单的示例代码:

function hey(){
  return;
}
hey.sayHello = function(name) {
  console.log('Hello ' + name);
} 
hey.sayHello('John'); //=> Hello John

这基本上就是他们正在做的,只是要复杂得多,还有更多的事情要做

module.exports = Format;

当您将require('./formatting') 时,这将返回Format构造函数

另一方面,下面的代码将返回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());