Files लिखना
writeFile आपके content के साथ एक file बनाता है या अगर exist करती हो इसे replace करता है।
In this page:
Syntax
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
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. #}
आम गलतियां
- accidentally एक file overwrite करना
- stringify के बिना objects लिखना
- यह भूल जाना कि 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: