← Back to Tutorials Chapter 4

Node.js Core Modules

Node.js provides a rich set of built-in modules that don't require any installation. Here are the most commonly used ones.

HTTP/HTTPS

The http and https modules allow you to create web servers and make HTTP requests.

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

File System (fs)

The fs module provides an API for interacting with the file system.

const fs = require('fs');
const fsPromises = require('fs').promises;

// Read file synchronously
const data = fs.readFileSync('file.txt', 'utf8');

// Read file asynchronously with callback
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Read file with promises (recommended)
async function read() {
  const data = await fsPromises.readFile('file.txt', 'utf8');
  console.log(data);
}

// Write to file
fs.writeFileSync('output.txt', 'Hello, Node!');

// Directory operations
fs.mkdirSync('new-folder', { recursive: true });
fs.readdirSync('.').forEach(file => console.log(file));

Path

The path module provides utilities for working with file and directory paths.

const path = require('path');

const filePath = '/users/node/app.js';

console.log(path.basename(filePath));    // app.js
console.log(path.dirname(filePath));     // /users/node
console.log(path.extname(filePath));     // .js
console.log(path.parse(filePath));       // { root, dir, base, ext, name }

// Join paths safely
const fullPath = path.join(__dirname, 'public', 'index.html');
console.log(fullPath);

// Resolve to absolute path
console.log(path.resolve('src', 'index.js'));

OS

The os module provides operating system-related utility methods.

const os = require('os');

console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('CPUs:', os.cpus().length);
console.log('Total Memory:', os.totalmem());
console.log('Free Memory:', os.freemem());
console.log('Home Dir:', os.homedir());
console.log('Hostname:', os.hostname());
console.log('Network Interfaces:', os.networkInterfaces());

URL

const url = require('url');

const myUrl = new URL('https://example.com:8080/path?name=node&version=18');
console.log('Protocol:', myUrl.protocol);
console.log('Host:', myUrl.host);
console.log('Pathname:', myUrl.pathname);
console.log('Query Params:', myUrl.searchParams.get('name'));

// Format URL
console.log(myUrl.toString());

Events

Node.js has a built-in event system that many modules use. The events module provides the EventEmitter class.

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

myEmitter.on('customEvent', (arg) => {
  console.log('Event fired with:', arg);
});

myEmitter.emit('customEvent', { data: 'Hello' });

Streams

Streams are used to handle large amounts of data efficiently by processing chunks instead of loading everything into memory.

const fs = require('fs');
const zlib = require('zlib');

// Readable stream
const readStream = fs.createReadStream('input.txt', 'utf8');
// Writable stream
const writeStream = fs.createWriteStream('output.txt');

// Pipe data from read stream to write stream
readStream.pipe(writeStream);

// Chain transforms (compress)
fs.createReadStream('input.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('input.txt.gz'));

Buffers

Buffers handle raw binary data in Node.js.

// Create a buffer
const buf = Buffer.from('Hello, Node!');
console.log(buf);               // 
console.log(buf.toString());    // Hello, Node!
console.log(buf.length);        // 12

// Buffer operations
const buf2 = Buffer.alloc(10);
buf2.write('Hi');
console.log(buf2.toString());   // Hi

// Concatenate buffers
const combined = Buffer.concat([buf, Buffer.from(' World')]);
console.log(combined.toString()); // Hello, Node! World

Crypto

const crypto = require('crypto');

// Create a hash
const hash = crypto.createHash('sha256')
  .update('Hello, Node!')
  .digest('hex');
console.log('Hash:', hash);

// Generate random bytes
const randomBytes = crypto.randomBytes(16);
console.log('Random:', randomBytes.toString('hex'));

// Create HMAC
const hmac = crypto.createHmac('sha256', 'secret-key')
  .update('message')
  .digest('hex');

Other Notable Core Modules

Exercise: Build a simple CLI tool that reads a file, compresses it with zlib, calculates the SHA-256 hash of the original content, logs the current memory usage and CPU count, and writes the hash to a metadata file.