Node.js: Code Outside the Browser / Working with Modules

Built-in modules: fs, path, url, os, http, events

1. fs Module

the file system (fs) module allows you to work with the file system on your computer

const fs = require('fs');

fs.writeFileSync('hello.txt', 'Hello, Node!');
const content = fs.readFileSync('hello.txt', 'utf8');
console.log(content); // ➤ Hello, Node!

2.path — File Paths & Extensions

Helps you work with file and directory paths across platforms.

const path = require('path');

console.log(path.basename('/folder/hello.txt'));   // ➤ hello.txt
console.log(path.extname('hello.txt'));            // ➤ .txt
console.log(path.join(__dirname, 'file.js'));      // ➤ joins paths properly

3.url — Parse and Format URLs

Lets you work with and break down URLs.

const url = require('url');

const myURL = new URL('<https://example.com/about?name=Vee>');

console.log(myURL.pathname);   // ➤ /about
console.log(myURL.searchParams.get('name'));  // ➤ Vee

4.os — System Information

Use it to get info about the computer the Node app is running on.

const os = require('os');

console.log(os.platform());        // ➤ win32 / linux / darwin
console.log(os.freemem());         // ➤ Free RAM in bytes
console.log(os.cpus().length);     // ➤ Number of CPU cores

Useful for system monitoring tools or CLI apps.


5.http — Creating Web Servers (No Express Needed)

You can use this to create a web server from scratch.

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello from Node server!');
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

6.events — Event Handling System

Use it to emit and listen to events, like custom triggers.

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('greet', () => {
  console.log('👋 Hello!');
});

emitter.emit('greet');  // Triggers the event