Node.js
Node.js Stream & Buffers
brightlightkim
2022. 3. 19. 08:48
Streams
sart using data, before it has finished loading.
- ex) Before all the data could be stored >> we can pass it as a stream (Buffer)
- ex) Send down it every time it fills.
const readStream = fs.createReadStream('../docs/blog3.txt', {encoding: 'utf8'});
const writeStream = fs.createWriteStream('../docs/blog4.txt');
readStream.on('data', (chunk) =>{ //chunk: chunk of data.
//on is event listener.
//fire the call back data
console.log('----new Chunk ----');
console.log(chunk);
writeStream('\n NewChunk \n'); //pass data through a stream.
writeStream.write(chunk);
})
Easier Way
//shorter way: Piping
const writeStream = fs.createWriteStream('../docs/blog4.txt');
readStream.pipe(writeStream);
from 2 of Node.js Crash Course Tutorial