Writing files
writeFile creates a file with your content or replaces it if it exists.
In this page:
Syntax
fs.writeFileSync('path', data);
fs.writeFile('path', data, (err) => {
// handle err
});
Writing files
fs.writeFile, writeFileSync and fs.promises.writeFile overwrite existing files. The flag option controls behaviour, for example wx fails if the file already exists. Writing JSON is a matter of JSON.stringify first.
Note:
Write to a temp file and rename it for atomic updates.
Example: Writing files
const fs = require("fs");
fs.writeFileSync("user.json", JSON.stringify({ name: "Ada", age: 36 }, null, 2));
console.log(fs.readFileSync("user.json", "utf8"));
try { fs.writeFileSync("user.json", "x", { flag: "wx" }); } catch (e) { console.log("wx blocked:", e.code); }
// Output:
// {
// "name": "Ada",
// "age": 36
// }
// wx blocked: EEXIST
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Overwriting a file by accident
- Writing objects without stringify
- Forgetting file paths are relative to cwd
Chapter Summary
- writeFile overwrites
- flag wx prevents overwrites
- Stringify objects first
- Paths are relative to the working directory
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: