Code
nodejs
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);
});