Node.js
fs Module
Read, write, and watch files with promises and callbacks.
By EZ4Code Team
fsfilestream
Code
import { promises as fs } from "fs";
import { watch } from "fs";
// Async/await with promises API
async function readJson(path) {
const raw = await fs.readFile(path, "utf8");
return JSON.parse(raw);
}
// Write a file atomically (write to temp, rename)
async function writeJson(path, data) {
const tmp = path + ".tmp";
await fs.writeFile(tmp, JSON.stringify(data, null, 2));
await fs.rename(tmp, path);
}
// Streaming a large file
import { createReadStream, createWriteStream } from "fs";
createReadStream("input.bin")
.pipe(createWriteStream("output.bin"))
.on("finish", () => console.log("done"));
// Watch a file for changes
watch("./config.json", (eventType, filename) => {
console.log(eventType, filename);
});Explanation
Node's fs.promises API offers async/await-friendly file operations without callback pyramids. Writing to a temp file and renaming is atomic on POSIX, preventing partial reads. createReadStream pipes large files in chunks, avoiding loading them entirely into memory.
More Node.js Snippets
HTTP Server
Build an HTTP server with the http module and routing.
Streams
Pipe, transform, and consume streams efficiently.
EventEmitter
Emit and listen for custom events.
path Module
Join, resolve, and parse file paths cross-platform.
Buffers
Work with binary data using Buffer and TypedArrays.
Child Process
Spawn, exec, and fork external processes.