Node.jsМодуль 1: Введение в Node.js
Модульная система
CommonJS и ES Modules в Node.js
Цель урока
В этом уроке ты научишься:
- Использовать CommonJS модули
- Использовать ES Modules
- Понимать разницу между ними
CommonJS (CJS)
Стандартная модульная система Node.js.
Экспорт
// math.js
// Способ 1: module.exports
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// Способ 2: exports (сокращение)
exports.multiply = (a, b) => a * b;
exports.divide = (a, b) => a / b;
// Способ 3: одна функция/класс
module.exports = function greet(name) {
return `Привет, ${name}!`;
};Импорт
// app.js
// Импорт объекта
const math = require('./math');
console.log(math.add(2, 3)); // 5
// Деструктуризация
const { add, subtract } = require('./math');
console.log(add(2, 3)); // 5
// Встроенные модули
const fs = require('fs');
const path = require('path');
// npm пакеты
const express = require('express');Особенности CommonJS
// Кэширование — модуль загружается один раз
const mod1 = require('./module');
const mod2 = require('./module');
console.log(mod1 === mod2); // true
// Условный импорт
if (process.env.NODE_ENV === 'development') {
const debug = require('./debug');
}
// Динамический путь
const moduleName = 'math';
const mod = require(`./${moduleName}`);ES Modules (ESM)
Современная модульная система JavaScript.
Настройка
Добавь в package.json:
{
"type": "module"
}Или используй расширение .mjs.
Экспорт
// math.mjs или math.js (с "type": "module")
// Именованный экспорт
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// Экспорт по умолчанию
export default function multiply(a, b) {
return a * b;
}
// Экспорт в конце файла
const PI = 3.14159;
const E = 2.71828;
export { PI, E };Импорт
// app.mjs
// Именованный импорт
import { add, subtract } from './math.mjs';
// Импорт по умолчанию
import multiply from './math.mjs';
// Комбинация
import multiply, { add, subtract } from './math.mjs';
// Импорт всего
import * as math from './math.mjs';
console.log(math.add(2, 3));
// Переименование
import { add as sum } from './math.mjs';
// Встроенные модули
import fs from 'fs';
import { readFile } from 'fs/promises';Динамический импорт
// Работает и в CJS, и в ESM
async function loadModule() {
const module = await import('./math.mjs');
console.log(module.add(2, 3));
}
// Условный импорт
if (condition) {
const { feature } = await import('./feature.mjs');
}Сравнение CJS и ESM
| Особенность | CommonJS | ES Modules |
|---|---|---|
| Синтаксис | require, module.exports | import, export |
| Загрузка | Синхронная | Асинхронная |
| Кэширование | Да | Да |
| Top-level await | Нет | Да |
__dirname | Да | Нужен workaround |
| Динамический импорт | require(var) | import() |
| Расширение | .js, .cjs | .mjs или "type": "module" |
Встроенные модули
Основные модули
// Файловая система
const fs = require('fs');
const fsPromises = require('fs/promises');
// Пути
const path = require('path');
// HTTP
const http = require('http');
const https = require('https');
// События
const EventEmitter = require('events');
// Потоки
const { Readable, Writable } = require('stream');
// Утилиты
const util = require('util');
// URL
const { URL, URLSearchParams } = require('url');
// Криптография
const crypto = require('crypto');
// Дочерние процессы
const { exec, spawn } = require('child_process');
// Операционная система
const os = require('os');Создание модуля
Структура
my-module/
├── index.js
├── lib/
│ ├── utils.js
│ └── helpers.js
└── package.jsonindex.js
// Реэкспорт из других файлов
const utils = require('./lib/utils');
const helpers = require('./lib/helpers');
module.exports = {
...utils,
...helpers
};Практика
Задание 1: CommonJS модуль
Задача: Создай модуль калькулятора.
// calculator.js
// Экспортируй: add, subtract, multiply, divideРешение:
// calculator.js
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => b !== 0 ? a / b : null
};
// app.js
const calc = require('./calculator');
console.log(calc.add(10, 5)); // 15Задание 2: ES Module
Задача: Перепиши калькулятор на ES Modules.
Решение:
// calculator.mjs
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => b !== 0 ? a / b : null;
// app.mjs
import { add, multiply } from './calculator.mjs';
console.log(add(10, 5)); // 15Проверь себя
- Чем
module.exportsотличается отexports? - Как включить ES Modules в Node.js?
- Как сделать динамический импорт?