全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-15 7 分钟 ✍️ juanwangdev

Node.js 创建自定义模块

自定义模块让代码组织更清晰,通过 module.exports 导出,require 引入使用。

创建简单模块

JavaScript
// utils.js - 定义模块
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

// 导出模块
module.exports = {
  add,
  subtract
};
JavaScript
// app.js - 使用模块
const utils = require('./utils');

console.log(utils.add(5, 3));      // 8
console.log(utils.subtract(5, 3)); // 2

导出单个函数

JavaScript
// calculator.js
module.exports = function calculate(expression) {
  return eval(expression);
};

// 使用
const calculate = require('./calculator');
console.log(calculate('1 + 2')); // 3

导出类

JavaScript
// User.js
class User {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, I'm ${this.name}`;
  }
}

module.exports = User;

// 使用
const User = require('./User');
const user = new User('Tom', 25);
console.log(user.greet());

使用 exports 简写

JavaScript
// math.js
exports.add = (a, b) => a + b;
exports.multiply = (a, b) => a * b;
exports.divide = (a, b) => a / b;

// 等价于
module.exports.add = (a, b) => a + b;
module.exports.multiply = (a, b) => a * b;

// 使用
const math = require('./math');
console.log(math.add(1, 2));

exports 是 module.exports 的引用,不能直接赋值给 exports。

目录模块

将多个文件组织为目录模块:

JavaScript
// routes/index.js - 入口文件
const userRoutes = require('./users');
const productRoutes = require('./products');

module.exports = {
  userRoutes,
  productRoutes
};

// routes/users.js
module.exports = {
  getUser: (id) => { /* ... */ },
  createUser: (data) => { /* ... */ }
};

// routes/products.js
module.exports = {
  getProducts: () => { /* ... */ }
};

// 使用目录模块
const routes = require('./routes');
routes.userRoutes.getUser(1);

模块文件命名规范

JavaScript
// 推荐:小写字母,多个单词用连字符
// utils.js
// user-service.js
// api-handler.js

// 类模块:首字母大写
// User.js
// Database.js

// 私有模块:下划线开头
// _helper.js

相对路径引入

JavaScript
// 当前目录
const utils = require('./utils');

// 上级目录
const config = require('../config');

// 多级上级
const rootConfig = require('../../config');

模块拆分示例

JavaScript
// config/database.js
module.exports = {
  host: 'localhost',
  port: 3306,
  name: 'mydb'
};

// config/app.js
module.exports = {
  name: 'MyApp',
  version: '1.0.0',
  port: 3000
};

// config/index.js - 整合导出
const database = require('./database');
const app = require('./app');

module.exports = { database, app };

// 使用
const config = require('./config');
console.log(config.database.host);
console.log(config.app.name);

要点总结

  • 使用 module.exports 导出模块内容
  • exports 是 module.exports 的引用,只能添加属性
  • 目录模块用 index.js 作为入口
  • 类模块导出构造函数,函数模块导出函数或对象
  • 使用相对路径引入本地模块

📝 发现内容有误?点击此处直接编辑

← 上一篇 Node.js 内置模块
下一篇 → Node.js 模块加载机制与缓存
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库