Stream के Basics
Streams आपको बड़े data को पूरा memory में load करने की बजाय एक बार में एक piece process करने देते हैं।
In this page:
Syntax
const fs = require('fs');
const readable = fs.createReadStream('input');
const writable = fs.createWriteStream('output');
readable.pipe(writable);
Stream Basics
Streams की चार kinds हैं: readable, writable, duplex, और transform। आप इन्हें pipe या stream.pipeline function से connect करते हैं, जो errors भी handle करता है। Streaming वह तरीका है जिससे Node tiny memory के साथ huge files copy करता है।
Note:
जब आपको reliable error handling चाहिए pipe की बजाय stream.pipeline इस्तेमाल करें।
उदाहरण: stream basics
const { Readable, Transform, Writable, pipeline } = require("stream");
const upper = new Transform({
transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); },
});
const out = [];
const sink = new Writable({ write(chunk, enc, cb) { out.push(chunk.toString()); cb(); } });
pipeline(Readable.from(["node ", "streams"]), upper, sink, (err) => {
console.log(err ? "failed" : "result: " + out.join(""));
});
// Output:
// result: NODE STREAMS
⚠️ 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. #}
आम गलतियां
- readFile से एक huge file पढ़ना और memory खत्म करना
- backpressure ignore करना
- stream errors handle करना भूल जाना
चैप्टर सारांश
- Streams data को chunks में process करते हैं
- चार types: readable, writable, duplex, transform
- pipe या pipeline इन्हें connect करता है
- बड़े data के लिए memory बचाता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: