需要时未定义节点模块

Node module is undefined when required

本文关键字:节点 模块 未定义      更新时间:2023-09-26

当我尝试需要一个节点模块时,我遇到了一个非常奇怪的错误。 为了说明这个问题,这是我试图要求的代码:

module.exports = (function(){
  this.say = function(message) {
    console.log(message);
  }
})();

现在,当我需要此模块时,当我尝试按如下方式使用它时,我得到"无法读取未定义的属性'说':

var person = require('./Person.js')
person.say('Hello World!');

然而,如果我按如下方式定义模块,它可以正常工作......

module.exports = {
    say : function(message) {
       console.log(message);
    }
};

我什至尝试了这种也有效的符号...

module.exports = new Person();
function Person(){
  this.say = function(message) {
    console.log(message);
  }
};

有谁知道为什么第一个符号不能正常工作?

原因是您的第一个表示法不返回要导出的任何内容。

module.exports = (function(){
  this.say = function(message) {
    console.log(message);
  }
  return this;
})();

我想这应该可以解决你的问题。

module.exports 是一个对象,将在require调用该文件时返回。因此,假设您要编写一个执行某些逻辑的库,有些是私有的,有些是公共的。并且你只想向其他人公开你的公共函数来调用,您的文件可能看起来像:

// Some require calls you maybe using in your lib
function privateFunc(s) {
  console.log(s);
}
function publicFunc(s) {
  privateFunc("new log: " + s);
}
module.exports = {
  log: publicFunc
}

稍后将按如下方式使用它:

var logger= require('myLib');
logger.log("my log");

这将输出:

new log: my log

这可能比你真正想要的更深,但它意味着理解事物的流程