Types के साथ File System
In this page:
import * as fs from "fs";
const data: string = fs.readFileSync("path", "utf-8");
fs.writeFileSync("path", data);
एक File पढ़ना
@types/node के against typed fs.readFileSync से एक file पढ़ना default रूप से एक Buffer return करता है, या एक string अगर आप second argument के रूप में utf-8 जैसी एक encoding pass करें — return type असल में उस argument के आधार पर बदलता है।
उदाहरण: Reading a File
// import * as fs from "fs";
// const buffer: Buffer = fs.readFileSync("data.txt");
// const text: string = fs.readFileSync("data.txt", "utf-8");
console.log("readFileSync's return type depends on the encoding argument");
Files लिखना
fs.writeFileSync से files लिखना data argument के रूप में एक string या Buffer accept करता है, और typed signature यह सुनिश्चित करती है कि आप पहले convert किए बिना गलती से एक plain object जैसी कोई चीज़ pass न करें।
उदाहरण: Writing Files
// import * as fs from "fs";
// fs.writeFileSync("out.txt", "hello");
console.log("writeFileSync accepts a string or Buffer as its data argument");
File Information Check करना
fs.statSync से file information check करना एक typed Stats object return करता है जो .isFile(), .isDirectory(), और .size जैसी properties expose करता है, आपको यह branch करने देते हुए कि आप असल में किस तरह की filesystem entry देख रहे हैं।
उदाहरण: Checking File Information
// import * as fs from "fs";
// const stats: fs.Stats = fs.statSync("data.txt");
// if (stats.isFile()) { console.log(stats.size); }
console.log("statSync returns a typed Stats object with isFile()/isDirectory()");
Typed File Data
Typed file data का मतलब है कि डिस्क से जो भी वापस पढ़ा गया है — खासकर JSON files — उसे किसी और untyped external input जैसा ही treat करना: इसे parse करें, फिर इसे अपने expected type के रूप में trust करने से पहले इसके shape को validate करें।
उदाहरण: Typed File Data
interface Config { debug: boolean }
// const raw = fs.readFileSync("config.json", "utf-8");
const raw = '{"debug": true}';
const config: Config = JSON.parse(raw);
console.log(config.debug);
File Errors Handle करना
File errors handle करने का मतलब है इन synchronous calls से exceptions catch करना (या उनके async counterparts से rejected promises) और caught value को unknown से narrow करना, क्योंकि Node के fs errors एक .code property रखते हैं जैसे ENOENT जो plain Error guarantee नहीं करता।
उदाहरण: Handling File Errors
try {
// fs.readFileSync("missing.txt");
throw { code: "ENOENT", message: "file not found" };
} catch (err: unknown) {
const e = err as { code?: string };
console.log("Error code:", e.code);
}
readFileSync("data.txt")को एक string treat करना, जब बिना encoding के यह एकBufferreturn करता है।- File text पर
JSON.parseउपयोग करना और result को trust करना, क्योंकि यहanyहै और validate किया जाना चाहिए। - एक busy server में sync methods उपयोग करना, जो event loop block करता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: