JavaScript and TypeScript course ยท Module 5: Advanced JavaScript
CommonJS (require/module.exports)
In this lesson11
In the previous exercise we learned about ES Modules - JavaScript's modern module system. Now we'll dive into another, older but still very important module system: CommonJS. Although our Jurassic Park needs the latest technologies to monitor dinosaurs in the browser, its solid server-side infrastructure is built on Node.js, where CommonJS dominates.
What is CommonJS?
CommonJS is a module system created primarily with server-side environments in mind, and it has become the standard in the Node.js ecosystem. It provides a way to organize JavaScript code into separate modules, similar to ES Modules, but with different syntax and behavior.
Unlike ES Modules, which were added to JavaScript in ES6 (2015), CommonJS existed earlier and became the de facto standard for Node.js. Even now, despite official ES Modules support in Node.js, CommonJS remains the dominant format for Node.js modules and in the npm ecosystem.
CommonJS Basics
The main CommonJS concepts are:
- The
require()function for importing modules - The
module.exportsorexportsobject for exporting elements
Let's see how these work in the context of our Jurassic Park system.
Exporting Elements in CommonJS
1. Exporting by Assignment to module.exports
The simplest way to export is by assigning a value to module.exports:
// dinosaur.js - Dinosaur model
class Dinosaur {
constructor(name, species, diet, dangerLevel) {
this.name = name;
this.species = species;
this.diet = diet;
this.dangerLevel = dangerLevel;
this.health = 100;
this.isContained = true;
}
feed() {
this.health = Math.min(100, this.health + 20);
return `${this.name} has been fed. Health level: ${this.health}%`;
}
checkStatus() {
return {
name: this.name,
health: this.health,
isContained: this.isContained,
warning: this.dangerLevel > 7 ? "HIGH DANGER LEVEL" : ""
};
}
}
// Export the entire class
module.exports = Dinosaur;2. Exporting an Object with Multiple Elements
We can also export multiple elements by assigning an object to module.exports:
// securityUtils.js - Security utility functions
const SECURITY_LEVELS = {
GREEN: "normal",
YELLOW: "elevated",
ORANGE: "high",
RED: "critical"
};
function checkFenceStatus(sectorId) {
// Simulate checking fence status in a given sector
const status = Math.random() > 0.1 ? "active" : "failure";
return {
sector: sectorId,
status,
timestamp: new Date().toISOString()
};
}
function triggerAlarm(sector, reason) {
console.log(`ALARM! Sector ${sector}: ${reason}`);
// Alarm activation logic
return {
success: true,
alarmId: "ALR-" + Math.floor(Math.random() * 10000)
};
}
function getSecurityStatus() {
// Returns overall park security status
return {
level: SECURITY_LEVELS.GREEN,
activeAlarms: 0,
lastChecked: new Date().toISOString()
};
}
// Export multiple elements as an object
module.exports = {
SECURITY_LEVELS,
checkFenceStatus,
triggerAlarm,
getSecurityStatus
};3. Incrementally Adding to exports
We can also add exports one by one using the exports object (which is a reference to module.exports):
// parkStats.js - Jurassic Park statistics
let totalVisitors = 0;
let revenue = 0;
const incidents = [];
// Export first function
exports.addVisitors = function(count) {
totalVisitors += count;
return totalVisitors;
};
// Export second function
exports.addRevenue = function(amount) {
revenue += amount;
return revenue;
};
// Export third function
exports.recordIncident = function(type, location, description) {
const incident = {
id: incidents.length + 1,
type,
location,
description,
timestamp: new Date().toISOString()
};
incidents.push(incident);
return incident;
};
// Export fourth function
exports.getDailyStats = function() {
return {
totalVisitors,
revenue,
incidentCount: incidents.length
};
};NOTE: Remember that exports is just a reference to module.exports. If you assign something directly to module.exports, you lose that reference, so you cannot mix these styles in one file:
// This will NOT work
exports.someFunction = function() { /* ... */ };
module.exports = SomeClass; // This overwrites the previous export
// This will work
exports.someFunction = function() { /* ... */ };
exports.SomeClass = SomeClass;
// This will work too
module.exports.someFunction = function() { /* ... */ };
module.exports.SomeClass = SomeClass;
// And this will work (assigning the whole object)
module.exports = {
someFunction: function() { /* ... */ },
SomeClass: SomeClass
};Importing Modules in CommonJS
1. Importing an Entire Module
// app.js
const Dinosaur = require('./dinosaur.js');
// Create new dinosaur instances
const trex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore", 9);
const brachi = new Dinosaur("Longneck", "Brachiosaurus", "herbivore", 4);
console.log(trex.checkStatus());
console.log(brachi.feed());2. Importing and Destructuring
// securityMonitor.js
const security = require('./securityUtils.js');
// Use imported functions and constants from the object
function monitorSecurity() {
const sectors = ["A1", "B2", "C3", "D4"];
// Check each sector
sectors.forEach(sector => {
const fenceStatus = security.checkFenceStatus(sector);
if (fenceStatus.status === "failure") {
const alarmResult = security.triggerAlarm(
sector,
"Electric fence failure!"
);
console.log(`Alarm ${alarmResult.alarmId} triggered in sector ${sector}`);
// Update security status
console.log("Changing security level to:", security.SECURITY_LEVELS.RED);
}
});
}
setInterval(monitorSecurity, 60000); // Check every minute3. Destructuring on Import
In newer Node.js versions we can also use destructuring directly on import:
// dashboard.js
const { checkFenceStatus, triggerAlarm, SECURITY_LEVELS } = require('./securityUtils.js');
// Now we can use functions directly
function checkAllSectors() {
["A1", "B2", "C3", "D4"].forEach(sector => {
console.log(`Checking sector ${sector}: `, checkFenceStatus(sector));
// Use the imported constant
if (Math.random() < 0.1) {
console.log(`Setting security level: ${SECURITY_LEVELS.ORANGE}`);
}
});
}Differences Between CommonJS and ES Modules
It's important to understand the key differences between CommonJS and ES Modules:
| Feature | CommonJS | ES Modules |
|---|---|---|
| Import syntax | require() | import ... from ... |
| Export syntax | module.exports = ... or exports.x = ... | export ... or export default ... |
| Loading | Synchronous | Asynchronous (loaded before execution) |
| Execution | Code executed on each import | Code executed only once, then module is cached |
| Static analysis | Not supported (dynamic paths) | Supported (paths are static) |
| Browser support | Not natively supported | Supported in modern browsers |
| Hoisting | Imports are not hoisted | Imports are hoisted (usable before declaration) |
| Tree-shaking | Harder to implement | Easier due to static analysis |
Node.js Project Structure (Jurassic Park Backend)
Let's look at how we might organize the backend of our Jurassic Park management system using Node.js and CommonJS:
jurassic-park-backend/
โโโ config/
โ โโโ database.js # Database configuration
โ โโโ environment.js # Environment variables
โ โโโ security.js # Security settings
โโโ models/
โ โโโ dinosaur.js # Dinosaur model
โ โโโ employee.js # Employee model
โ โโโ facility.js # Facility model
โ โโโ index.js # Model aggregator
โโโ controllers/
โ โโโ dinosaurController.js # Dinosaur controller
โ โโโ securityController.js # Security controller
โ โโโ employeeController.js # Employee controller
โโโ routes/
โ โโโ api.js # Main API router
โ โโโ dinosaurs.js # Dinosaur-related routes
โ โโโ security.js # Security-related routes
โโโ services/
โ โโโ monitoringService.js # Monitoring service
โ โโโ notificationService.js # Notification service
โ โโโ loggingService.js # Logging service
โโโ utils/
โ โโโ logger.js # Logging utility
โ โโโ validators.js # Data validators
โโโ middleware/
โ โโโ auth.js # Authentication middleware
โ โโโ errorHandler.js # Error handling
โโโ app.js # Main application
โโโ server.js # Server startup fileLet's look at example implementations of these modules:
Configuration File (config/database.js)
// config/database.js
module.exports = {
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 27017,
name: process.env.DB_NAME || 'jurassic_park',
user: process.env.DB_USER || 'admin',
password: process.env.DB_PASSWORD || 'secret',
// Helper function to build the connection URI
getConnectionString: function() {
return `mongodb://${this.user}:${this.password}@${this.host}:${this.port}/${this.name}`;
}
};Model (models/dinosaur.js)
// models/dinosaur.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Dinosaur schema
const dinosaurSchema = new Schema({
name: { type: String, required: true },
species: { type: String, required: true },
diet: { type: String, enum: ['carnivore', 'herbivore', 'omnivore'], required: true },
dangerLevel: { type: Number, min: 1, max: 10, required: true },
enclosureId: { type: Schema.Types.ObjectId, ref: 'Enclosure' },
health: { type: Number, default: 100 },
status: {
isContained: { type: Boolean, default: true },
lastCheck: { type: Date, default: Date.now }
},
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
// Schema methods
dinosaurSchema.methods.feed = function() {
this.health = Math.min(100, this.health + 20);
this.updatedAt = Date.now();
return this.save();
};
dinosaurSchema.methods.checkStatus = function() {
return {
name: this.name,
health: this.health,
isContained: this.status.isContained,
warning: this.dangerLevel > 7 ? "HIGH DANGER LEVEL" : ""
};
};
// Static methods
dinosaurSchema.statics.findDangerous = function() {
return this.find({ dangerLevel: { $gte: 8 } });
};
// Pre-save hook
dinosaurSchema.pre('save', function(next) {
this.updatedAt = Date.now();
next();
});
// Create the model
const Dinosaur = mongoose.model('Dinosaur', dinosaurSchema);
// Export the model
module.exports = Dinosaur;Controller (controllers/dinosaurController.js)
// controllers/dinosaurController.js
const Dinosaur = require('../models/dinosaur');
const logger = require('../utils/logger');
// Controller object with multiple methods
const dinosaurController = {
// Get all dinosaurs
getAllDinosaurs: async (req, res) => {
try {
const dinosaurs = await Dinosaur.find().populate('enclosureId');
res.json(dinosaurs);
} catch (error) {
logger.error('Error fetching dinosaurs:', error);
res.status(500).json({ error: 'Server error' });
}
},
// Get dinosaur by ID
getDinosaurById: async (req, res) => {
try {
const dinosaur = await Dinosaur.findById(req.params.id).populate('enclosureId');
if (!dinosaur) {
return res.status(404).json({ error: 'Dinosaur not found' });
}
res.json(dinosaur);
} catch (error) {
logger.error(`Error fetching dinosaur ID=${req.params.id}: `, error);
res.status(500).json({ error: 'Server error' });
}
},
// Add a new dinosaur
createDinosaur: async (req, res) => {
try {
const { name, species, diet, dangerLevel, enclosureId } = req.body;
const newDinosaur = new Dinosaur({
name,
species,
diet,
dangerLevel,
enclosureId
});
await newDinosaur.save();
logger.info(`Added new dinosaur: ${name} (${species})`);
res.status(201).json(newDinosaur);
} catch (error) {
logger.error('Error creating dinosaur:', error);
res.status(400).json({ error: error.message });
}
},
// Feed a dinosaur
feedDinosaur: async (req, res) => {
try {
const dinosaur = await Dinosaur.findById(req.params.id);
if (!dinosaur) {
return res.status(404).json({ error: 'Dinosaur not found' });
}
await dinosaur.feed();
logger.info(`Fed dinosaur: ${dinosaur.name}`);
res.json({
message: `${dinosaur.name} has been fed. Health level: ${dinosaur.health}%`,
health: dinosaur.health
});
} catch (error) {
logger.error(`Error feeding dinosaur ID=${req.params.id}: `, error);
res.status(500).json({ error: 'Server error' });
}
},
// Find dangerous dinosaurs
getDangerousDinosaurs: async (req, res) => {
try {
const dangerousDinos = await Dinosaur.findDangerous();
res.json(dangerousDinos);
} catch (error) {
logger.error('Error fetching dangerous dinosaurs:', error);
res.status(500).json({ error: 'Server error' });
}
}
};
// Export the entire controller object
module.exports = dinosaurController;Routes (routes/dinosaurs.js)
// routes/dinosaurs.js
const express = require('express');
const router = express.Router();
const dinosaurController = require('../controllers/dinosaurController');
const authMiddleware = require('../middleware/auth');
// Dinosaur-related routes
router.get('/', dinosaurController.getAllDinosaurs);
router.get('/dangerous', dinosaurController.getDangerousDinosaurs);
router.get('/:id', dinosaurController.getDinosaurById);
// Routes requiring authentication
router.post('/', authMiddleware.verifyToken, dinosaurController.createDinosaur);
router.post('/:id/feed', authMiddleware.verifyToken, dinosaurController.feedDinosaur);
// Export the router
module.exports = router;Main Application File (app.js)
// app.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
// Config and middleware imports
const dbConfig = require('./config/database');
const errorHandler = require('./middleware/errorHandler');
const logger = require('./utils/logger');
// Route imports
const apiRouter = require('./routes/api');
const dinosaurRoutes = require('./routes/dinosaurs');
const securityRoutes = require('./routes/security');
// Initialize Express app
const app = express();
// Middleware
app.use(helmet()); // Security
app.use(cors()); // Cross-Origin Resource Sharing
app.use(morgan('dev')); // HTTP request logging
app.use(express.json()); // JSON parsing
app.use(express.urlencoded({ extended: false })); // Form parsing
// Connect to database
mongoose.connect(dbConfig.getConnectionString(), {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
logger.info('Connected to MongoDB database');
})
.catch(err => {
logger.error('Database connection error:', err);
process.exit(1);
});
// Routes
app.use('/api', apiRouter);
app.use('/api/dinosaurs', dinosaurRoutes);
app.use('/api/security', securityRoutes);
// Handle 404 errors
app.use((req, res, next) => {
res.status(404).json({ error: 'Not found' });
});
// Centralized error handling
app.use(errorHandler);
// Export the application
module.exports = app;Server Startup File (server.js)
// server.js
const http = require('http');
const app = require('./app');
const logger = require('./utils/logger');
// Port settings
const port = process.env.PORT || 3000;
app.set('port', port);
// Create HTTP server
const server = http.createServer(app);
// Listen for connections
server.listen(port, () => {
logger.info(`Jurassic Park server started on port ${port}`);
});
// Handle server errors
server.on('error', (error) => {
if (error.syscall !== 'listen') {
throw error;
}
logger.error(`Server error: ${error}`);
process.exit(1);
});Circular Dependencies
One challenge when working with CommonJS (and modules in general) is circular dependencies, which occur when module A imports module B and module B imports module A:
// dinosaurUtils.js
const Dinosaur = require('./dinosaur');
function isDangerous(dino) {
return dino.dangerLevel > 7;
}
module.exports = { isDangerous };
// dinosaur.js
const dinosaurUtils = require('./dinosaurUtils'); // Circular dependency!
class Dinosaur {
// ... class implementation
isHighRisk() {
return dinosaurUtils.isDangerous(this);
}
}
module.exports = Dinosaur;CommonJS handles circular dependencies, but it can lead to strange behavior like incomplete objects. To avoid such problems:
- Restructure the code to avoid circular dependencies
- Use the dependency injection pattern
- Move shared code to a third module that both import from
Transpiling CommonJS to ES Modules and Back
In many projects we need to handle both CommonJS and ES Modules. For example, the frontend of our Jurassic Park might use ES Modules while the backend uses CommonJS. What do we do when we want to share code?
Babel for Transpilation
We can use Babel to transpile between formats:
// babel.config.js for ES Modules -> CommonJS
module.exports = {
presets: [
['@babel/preset-env', {
targets: {
node: 'current'
},
modules: 'commonjs' // Convert import/export to require/exports
}]
]
};Dual Package Hazard
Another approach is to create packages that support both module formats. In package.json you can define:
{
"name": "jurassic-park-utils",
"version": "1.0.0",
"main": "dist/index.js",
"module": "dist/index.mjs",
"exports": {
"import": "./dist/index.mjs",
"require": "./dist/index.js"
}
}Modern Approach: Node.js with ES Modules
Newer versions of Node.js (from 13.2.0) officially support ES Modules. We can enable this support in a few ways:
- Using the
.mjsextension for ES Module files - Setting
"type": "module"in package.json
However, many npm packages still use CommonJS, so you'll likely need to work with both systems.
Practical Example: Migrating from CommonJS to ES Modules
Let's say we want to migrate part of our backend from CommonJS to ES Modules. Here's how such a migration might look:
Original CommonJS Version (dinosaurController.js)
// controllers/dinosaurController.js (CommonJS)
const Dinosaur = require('../models/dinosaur');
const logger = require('../utils/logger');
function getAllDinosaurs(req, res) {
// implementation
}
function getDinosaurById(req, res) {
// implementation
}
module.exports = {
getAllDinosaurs,
getDinosaurById
};Migration to ES Modules (dinosaurController.mjs)
// controllers/dinosaurController.mjs (ES Modules)
import Dinosaur from '../models/dinosaur.mjs';
import logger from '../utils/logger.mjs';
export function getAllDinosaurs(req, res) {
// implementation
}
export function getDinosaurById(req, res) {
// implementation
}
// We can also export a default object with functions
export default {
getAllDinosaurs,
getDinosaurById
};Compatibility Wrapper
Sometimes we need to create a wrapper that allows importing an ES Module from CommonJS code:
// controllers/dinosaurControllerWrapper.js (CommonJS)
// This file loads an ES Module and exports it as CommonJS
const importESM = async () => {
const controller = await import('./dinosaurController.mjs');
return controller.default; // or selected functions
};
// Export a function that returns a Promise with the controller
module.exports = importESM();Summary
CommonJS is a widely used module system in Node.js that allows organizing code into separate modules, which is critical for building scalable applications like the backend of our Jurassic Park management system.
The main CommonJS concepts are:
- The
require()function for importing modules - The
module.exportsorexportsobject for exporting elements - Synchronous module loading
- Essential module caching for performance
Despite the growing popularity of ES Modules, CommonJS remains an important module system, especially in the Node.js ecosystem. Understanding the differences between CommonJS and ES Modules is key to effectively developing JavaScript applications that can run both in the browser and on the server.
In our Jurassic Park, we use CommonJS for the backend (monitoring, database, security control) and ES Modules for the frontend (user interface, dashboards, notifications). This combination gives us the best of both worlds and lets us efficiently manage a system that must be reliable - after all, the safety of the park and its guests depends on our code!
In the next exercise we'll look at dynamic module importing, which provides even greater flexibility in loading code on demand, which can be critical in emergency situations at Jurassic Park.
Code for this lesson: main.js
// CommonJS in Jurassic Park - Node.js backend
// Demo of the require/module.exports system
console.log("Jurassic Park backend - CommonJS");
console.log("Node.js server management system\n");
// ===========================================
// CommonJS module simulation
// ===========================================
// === dinosaur.js - Dinosaur model (CommonJS) ===
class Dinosaur {
constructor(name, species, diet, dangerLevel) {
this.name = name;
this.species = species;
this.diet = diet;
this.dangerLevel = dangerLevel;
this.health = 100;
this.id = `DINO-${Math.random().toString(36).substr(2, 9).toUpperCase()}`;
}
feed() {
this.health = Math.min(100, this.health + 20);
return { success: true, message: `${this.name} fed`, health: this.health };
}
getDetails() {
return {
id: this.id,
name: this.name,
species: this.species,
diet: this.diet,
dangerLevel: this.dangerLevel,
health: this.health
};
}
}
// CommonJS export - main class
const DinosaurModule = Dinosaur;
// === database.js - Database simulation (CommonJS) ===
const database = {
dinosaurs: new Map(),
enclosures: new Map(),
logs: []
};
function saveDinosaur(dinosaur) {
database.dinosaurs.set(dinosaur.id, dinosaur);
database.logs.push({ action: 'SAVE_DINOSAUR', id: dinosaur.id, timestamp: Date.now() });
return { success: true, id: dinosaur.id };
}
function getDinosaur(id) {
const dino = database.dinosaurs.get(id);
return dino || null;
}
function getAllDinosaurs() {
return Array.from(database.dinosaurs.values());
}
function deleteDinosaur(id) {
const deleted = database.dinosaurs.delete(id);
if (deleted) {
database.logs.push({ action: 'DELETE_DINOSAUR', id, timestamp: Date.now() });
}
return { success: deleted };
}
function getDatabaseStats() {
return {
dinosaurCount: database.dinosaurs.size,
enclosureCount: database.enclosures.size,
totalLogs: database.logs.length
};
}
// CommonJS multiple exports
const DatabaseModule = {
saveDinosaur,
getDinosaur,
getAllDinosaurs,
deleteDinosaur,
getDatabaseStats
};
// === config.js - Configuration (CommonJS) ===
const config = {
server: {
port: 3000,
host: 'localhost',
environment: 'development'
},
database: {
url: 'mongodb://localhost:27017/jurassic-park',
maxConnections: 10
},
security: {
maxDangerLevel: 10,
alertThreshold: 7
},
park: {
maxDinosaurs: 50,
maxVisitors: 1000,
openingHours: { start: 9, end: 18 }
}
};
// CommonJS config export
const ConfigModule = config;
// === logger.js - Logging system (CommonJS) ===
const LOG_LEVELS = {
INFO: 'INFO',
WARN: 'WARN',
ERROR: 'ERROR',
DEBUG: 'DEBUG'
};
function formatLogMessage(level, message) {
const timestamp = new Date().toISOString();
return `[${timestamp}] [${level}] ${message}`;
}
function log(level, message) {
const formatted = formatLogMessage(level, message);
console.log(formatted);
database.logs.push({ level, message, timestamp: Date.now() });
}
function info(message) { log(LOG_LEVELS.INFO, message); }
function warn(message) { log(LOG_LEVELS.WARN, message); }
function error(message) { log(LOG_LEVELS.ERROR, message); }
function debug(message) { log(LOG_LEVELS.DEBUG, message); }
// CommonJS logger exports
const LoggerModule = {
LOG_LEVELS,
log,
info,
warn,
error,
debug
};
// === api-routes.js - API endpoints (CommonJS) ===
class DinosaurAPI {
static createDinosaur(req) {
const { name, species, diet, dangerLevel } = req.body;
LoggerModule.info(`Creating dinosaur: ${name}`);
const dinosaur = new DinosaurModule(name, species, diet, dangerLevel);
DatabaseModule.saveDinosaur(dinosaur);
LoggerModule.info(`Dinosaur created: ${dinosaur.id}`);
return {
status: 201,
data: dinosaur.getDetails()
};
}
static getDinosaur(req) {
const { id } = req.params;
LoggerModule.debug(`Fetching dinosaur: ${id}`);
const dinosaur = DatabaseModule.getDinosaur(id);
if (!dinosaur) {
LoggerModule.warn(`Dinosaur not found: ${id}`);
return {
status: 404,
error: 'Dinosaur not found'
};
}
return {
status: 200,
data: dinosaur.getDetails()
};
}
static listDinosaurs() {
LoggerModule.debug('Listing all dinosaurs');
const dinosaurs = DatabaseModule.getAllDinosaurs();
return {
status: 200,
data: dinosaurs.map(d => d.getDetails()),
count: dinosaurs.length
};
}
static deleteDinosaur(req) {
const { id } = req.params;
LoggerModule.info(`Deleting dinosaur: ${id}`);
const result = DatabaseModule.deleteDinosaur(id);
if (!result.success) {
return {
status: 404,
error: 'Dinosaur not found'
};
}
LoggerModule.info(`Dinosaur deleted: ${id}`);
return {
status: 200,
data: { deleted: true }
};
}
static getServerStats() {
LoggerModule.debug('Fetching server stats');
const dbStats = DatabaseModule.getDatabaseStats();
return {
status: 200,
data: {
...dbStats,
config: {
maxDinosaurs: ConfigModule.park.maxDinosaurs,
environment: ConfigModule.server.environment
}
}
};
}
}
// CommonJS API export
const APIModule = DinosaurAPI;
// ===========================================
// COMMONJS SYSTEM DEMO
// ===========================================
console.log("=== SERVER INITIALIZATION ===\n");
LoggerModule.info('Server starting...');
LoggerModule.info(`Port: ${ConfigModule.server.port}`);
LoggerModule.info(`Environment: ${ConfigModule.server.environment}`);
console.log("\n=== CREATING DINOSAURS (API CALLS) ===\n");
// API request simulation
const req1 = {
body: { name: 'Rexy', species: 'T-Rex', diet: 'carnivore', dangerLevel: 9 }
};
const response1 = APIModule.createDinosaur(req1);
console.log('POST /api/dinosaurs:', JSON.stringify(response1, null, 2));
const req2 = {
body: { name: 'Blue', species: 'Velociraptor', diet: 'carnivore', dangerLevel: 7 }
};
const response2 = APIModule.createDinosaur(req2);
console.log('\nPOST /api/dinosaurs:', JSON.stringify(response2, null, 2));
const req3 = {
body: { name: 'Gentle Giant', species: 'Brachiosaurus', diet: 'herbivore', dangerLevel: 2 }
};
const response3 = APIModule.createDinosaur(req3);
console.log('\nPOST /api/dinosaurs:', JSON.stringify(response3, null, 2));
console.log("\n=== FETCHING DATA (API CALLS) ===\n");
// List of all dinosaurs
const listResponse = APIModule.listDinosaurs();
console.log('GET /api/dinosaurs:', JSON.stringify(listResponse, null, 2));
console.log("\n=== SERVER STATISTICS ===\n");
const statsResponse = APIModule.getServerStats();
console.log('GET /api/stats:', JSON.stringify(statsResponse, null, 2));
console.log("\n=== DIFFERENCES: CommonJS vs ES Modules ===\n");
console.log("CommonJS (Node.js):");
console.log(" - Uses: require() and module.exports");
console.log(" - Synchronous loading");
console.log(" - Dynamic imports at runtime");
console.log(" - Value is copied\n");
console.log("ES Modules (ES6+):");
console.log(" - Uses: import and export");
console.log(" - Asynchronous loading");
console.log(" - Static imports at compile time");
console.log(" - Value is a reference (live binding)\n");
console.log("CommonJS example:");
console.log(" // dinosaur.js");
console.log(" module.exports = class Dinosaur { ... };");
console.log("");
console.log(" // main.js");
console.log(" const Dinosaur = require('./dinosaur');\n");
console.log("ES Modules example:");
console.log(" // dinosaur.js");
console.log(" export default class Dinosaur { ... }");
console.log("");
console.log(" // main.js");
console.log(" import Dinosaur from './dinosaur.js';\n");
LoggerModule.info('Demo completed successfully!');
console.log("\nJurassic Park backend ready!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Horizontal ordering
Arrange the function export elements: