As file gets bigger and bigger, we should not read the whole file and store it in a variable
Types
Writeable
Readable
Duplex
Used to both read and write data sequentially
Transform
Data can be modified while writing or reading
Example 1
Write.js
const { writeFileSync } =require('fs')for (let i=0; i <10000 ; i++) {writeFileSync('./file.txt',`hello world ${i}\n`, { flag:'a' })}
Reading.js
const { createReadStream } =require('fs')// Reading data in chunks of 90kb, default is 64kbconststream=createReadStream('./file.txt', { highWaterMark:90000, encoding:'utf8'});stream.on('data', (result) => {console.log(result)})stream.on('error', (error) => {console.log(error)})
Example 2
var http =require('http')var fs =require('fs')http.createServer(function (req, res) {// Sending Data at Once// const text = fs.readFileSync('./file.txt', 'utf8')// res.end(text)// Sending Data in ChunksconstfileStream=fs.createReadStream('./file.txt','utf8');fileStream.on('open', () => {fileStream.pipe(res) })fileStream.on('error', (err) => {res.end(err) })})