CommonJS 是 Node.js 默认模块系统,通过 module.exports 导出、require() 导入;exports 是其引用,可添加属性但不可重赋值;require 同步缓存,模块为单例。

在 Node.js 中,CommonJS 是默认的模块系统,使用 module.exports 和 require() 实现模块导出与导入。它语法简洁、运行时加载,是 Node.js 早期至今最广泛使用的模块规范。
基本导出方式:module.exports
module.exports 是模块对外暴露的唯一接口。你可以把它赋值为任意类型(对象、函数、字符串、数字等),其他文件通过 require() 获取的就是这个值。
- 导出一个对象:
module.exports = {
add: (a, b) => a + b,
multiply: (a, b) => a * b
};- 导出一个函数:
module.exports = function(name) {
return `Hello, ${name}!`;
};常用简写:exports 是 module.exports 的引用
exports 初始时指向 module.exports,因此可以给它添加属性,但不能直接赋值——否则会断开与 module.exports 的联系,导致导出为空。
- ✅ 正确(添加属性):
exports.log = console.log; exports.now = () => new Date();
- ❌ 错误(重赋值 exports):
exports = { log: console.log }; // 不生效!require() 得到的是空对象导出默认对象 + 额外命名导出(模拟 ES Module 风格)
虽然 CommonJS 没有 export default,但可通过组合方式实现类似效果:
Miller (mlr) 是一个命令行工具,用于查询、整形和重新格式化名称索引数据,如 CSV、TSV、JSON 和 JSON Lines。它将 awk、sed、cut、join 和 sort 的功能整合到一个专为结构化数据处理而构建的单一工具中。
立即学习“Java免费学习笔记(深入)”;
- 把主功能设为
module.exports,同时挂载其他工具到exports上:
const main = () => 'API ready';
<p>module.exports = main;
module.exports.version = '1.0.0';
module.exports.helpers = {
validate: (x) => typeof x === 'string'
};使用时:
const api = require('./api');
const { version, helpers } = require('./api'); // 解构也有效注意点:require 是同步且缓存的
require() 在首次加载后会将模块导出结果缓存(基于绝对路径),后续重复 require 返回同一份引用。这意味着:
- 模块内变量是单例,适合配置、连接池等场景
- 若需重新执行模块代码(如测试中),需手动清空
require.cache
不复杂但容易忽略细节,掌握 module.exports 的赋值本质就能稳妥使用 CommonJS。

















