Core Modules
The Standard Issue Utility Belt
Section titled “The Standard Issue Utility Belt”Imagine you just bought a high-end smartphone. Out of the box, even before you visit the App Store, it can already do a lot. It has a camera, a calculator, a file manager, and a web browser. You didn’t have to install them; they are effectively “baked in” to the factory settings.
Node.js Core Modules are exactly like that.
These are the “Factory Settings” of the Node runtime. They are essential tools that the Node team decided were so critical for server-side development that they shouldn’t require a download. They are part of the binary executable itself.
If Node.js is Batman, these modules are the utility belt he always wears.
The Distinction: Built-in vs. Installed
Section titled “The Distinction: Built-in vs. Installed”In the next few lessons, we’re going to use a tool called NPM (Node Package Manager) to download millions of community-created tools. But right now? We don’t need it.
We have access to powerful system-level operations immediately, but there is one catch: We still have to ask for them.
Even though they are built-in, Node doesn’t load them into global memory by default (to save resources). You must explicitly require() them.
// CORRECT: No path needed for core modulesconst fs = require('fs');
// INCORRECT: Node thinks this is a local file you madeconst fs = require('./fs');[!NOTE] Notice how we just type the name
"fs"? Node.js has a lookup priority. It checks for a Core Module with that name first. If it finds one, it loads it. If not, it looks for anode_modulesfolder.
The “Big Five”
Section titled “The “Big Five””There are many core modules, but as a backend developer, these are the ones you will reach for constantly:
- fs (File System): Read, write, and manipulate files on the hard drive. (Browser JavaScript wishes it could do this).
- path: A utility for normalizing file paths so your code doesn’t break between Windows (
\) and Mac/Linux (/). - http: The heavy lifter that allows us to create web servers and handle network requests.
- os: Provides information about the operating system (CPU info, memory usage, uptime).
- events: The backbone of Node’s asynchronous architecture (we’ll dive deep into this later).
Seeing them in action
Section titled “Seeing them in action”Here is a quick script that uses three different core modules to spy on your own computer.
const os = require('os');const path = require('path');const fs = require('fs');
// 1. Where are we?const currentFile = path.basename(__filename);
// 2. Who is the host?const user = os.userInfo().username;const memory = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2);
// 3. Write a reportconst report = ` SECURITY LOG: User: ${user} System Memory: ${memory} GB File Accessed: ${currentFile}`;
fs.writeFileSync('security.log', report);console.log('Report generated.');Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Core Modules Demo Repo
Node.js Modules Documentation