Files पढ़ना (sync/async)
आप एक file एक साथ पढ़ सकते हैं, या तो program block करते हुए या इसे block किए बिना।
In this page:
Syntax
const data = fs.readFileSync('path', 'utf8');
fs.readFile('path', 'utf8', (err, data) => {
// handle err, use data
});
Files पढ़ना (sync/async)
readFileSync तुरंत contents return करता है और block करता है। fs.readFile एक callback लेता है और fs.promises.readFile एक promise return करता है। दोनों को text return करने के लिए एक encoding चाहिए। ENOENT जैसी errors दिखाती हैं कि file missing है।
Note:
servers में async reads और start-up scripts में sync reads इस्तेमाल करें।
उदाहरण: Reading files (sync/async)
const fs = require("fs");
fs.writeFileSync("data.txt", "line one\nline two");
console.log(fs.readFileSync("data.txt", "utf8").split("\n"));
fs.readFile("data.txt", "utf8", (err, text) => console.log("async length:", text.length));
try { fs.readFileSync("missing.txt"); } catch (e) { console.log(e.code); }
// Output:
// [ 'line one', 'line two' ]
// ENOENT
// async length: 17
⚠️ 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. #}
आम गलतियां
- एक request handler में readFileSync इस्तेमाल करना
- encoding भूल जाना
- ENOENT catch न करना
चैप्टर सारांश
- readFileSync block करता है
- readFile callbacks इस्तेमाल करता है
- fs.promises promises return करता है
- Text के लिए utf8 pass करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: