File System and Path
Node.js comes bundled with heavily optimized native modules that interact directly with the host operating system. To use these core modules in code, you simply import them using the prefixed node: module tag.
The node:path Module
Due to structural string differences across different operating systems (Windows uses backslashes \, while Linux/Mac uses forward slashes /), manually typing hardcoded directory locations natively causes major deployment crashes.
The path module handles string standardization correctly for the physical execution environment natively.
import path from 'node:path';
// Safely joins string segments using the correct OS slash
const fullPath = path.join('users', 'admin', 'profile.txt');
// Outputs on Mac: 'users/admin/profile.txt'
// Outputs on Win: 'users\admin\profile.txt'
// Extracts the file extension natively
console.log(path.extname(fullPath)); // '.txt'
The node:fs/promises Module
The File System (fs) module specifically grants JavaScript read and write access directly to hardware disks cleanly. The modern fs/promises variant replaces ancient callback trees with modern asynchronous generic Promises.
Reading Files
import fs from 'node:fs/promises';
import path from 'node:path';
async function readFileContent() {
try {
const filePath = path.join(process.cwd(), 'data.txt');
// Reads the entire file into memory instantly
const data = await fs.readFile(filePath, 'utf8');
console.log(data);
} catch (error) {
console.error("Failed to specifically read the file: ", error);
}
}
readFileContent();
Writing Files
Overwriting existing files or creating new files logically is just as simple.
import fs from 'node:fs/promises';
async function saveLog() {
const content = "Server booted up cleanly at 12:00 PM.";
// Notice we don't need 'utf8' here, as strings write natively securely
await fs.writeFile('server.log', content);
}