MST

星途 面试题库

面试题:Node.js模块系统中exports与module.exports的区别

在Node.js模块系统里,exports和module.exports都与模块的导出相关,请详细阐述它们之间的区别,并且举例说明在何种场景下会使用到它们不同的导出方式。
23.4万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

区别

  1. 本质
    • exports 实际上是 module.exports 的一个引用。在Node.js模块的顶层作用域中,Node.js会自动创建一个 exports 对象,这个对象指向 module.exports
    • module.exports 是Node.js内部用于定义模块导出内容的核心对象。
  2. 赋值操作
    • 如果对 exports 进行重新赋值(例如 exports = { newProperty: 'newValue' }),这并不会影响 module.exports。因为此时 exports 指向了一个新的对象,不再与 module.exports 有引用关系。
    • module.exports 进行赋值(例如 module.exports = { newProperty: 'newValue' }),则会改变模块实际导出的内容,因为模块最终导出的就是 module.exports 指向的对象。

场景举例

  1. 使用 exports 导出单个属性或方法
    • 当你只想为模块导出一些简单的属性或方法时,可以直接使用 exports。例如,创建一个名为 mathUtils.js 的模块,用于导出一个简单的加法函数:
// mathUtils.js
exports.add = function(a, b) {
    return a + b;
};
  • 在其他模块中使用:
const mathUtils = require('./mathUtils');
console.log(mathUtils.add(2, 3));
  1. 使用 module.exports 导出复杂对象或构造函数
    • 当你需要导出一个复杂的对象,或者一个构造函数来创建实例时,更适合使用 module.exports。例如,创建一个 Person 类的模块 person.js
// person.js
function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.sayHello = function() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
};
module.exports = Person;
  • 在其他模块中使用:
const Person = require('./person');
const john = new Person('John', 30);
john.sayHello();
  • 又比如导出一个复杂的配置对象:
// config.js
module.exports = {
    database: {
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: 'password'
    },
    server: {
        port: 8080,
        hostname: '127.0.0.1'
    }
};
  • 在其他模块中使用:
const config = require('./config');
console.log(config.database.host);