← Back to Node.js Course | Chapter 5: File System | Lesson 2 of 7

Writing files

writeFile creates a file with your content or replaces it if it exists.

In this page:

  1. Writing files
Syntax
javascript
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

javascript
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
  1. Overwriting a file by accident
  2. Writing objects without stringify
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.