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

Files लिखना

writeFile आपके content के साथ एक file बनाता है या अगर exist करती हो इसे replace करता है।

In this page:

  1. Files लिखना
Syntax
javascript
fs.writeFileSync('path', data);
fs.writeFile('path', data, (err) => {
  // handle err
});

Files लिखना

fs.writeFile, writeFileSync, और fs.promises.writeFile existing files overwrite करते हैं। flag option behaviour control करता है, उदाहरण के लिए wx fail होता है अगर file already exist करती हो। JSON लिखना पहले JSON.stringify की बात है।

Note: Atomic updates के लिए एक temp file में लिखें और इसे rename करें।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. accidentally एक file overwrite करना
  2. stringify के बिना objects लिखना
  3. यह भूल जाना कि file paths cwd के relative हैं
चैप्टर सारांश
  • writeFile overwrite करता है
  • flag wx overwrites रोकता है
  • पहले objects stringify करें
  • Paths working directory के relative हैं
🔒

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.