Node.js

[Node.js] Streams Example

brightlightkim 2022. 4. 28. 02:15
const fs = require('fs');

//createReadStream: read the file
//first argument: location of the file
//second argument: option argument
//encoding: 'utf8' : enabled the readable format
const readStream = fs.createReadStream('./docs/blog3.txt', {encoding: 'utf8'});

//createWriteStream: write to the file
const writeStream = fs.createWriteStream('./docs/blog4.txt');


//on: file readevent listener
//everytime we receive the buffer of data, it performs
//chunk is the buffer of data

//write enabled to write it in the stream
readStream.on('data', (chunk) => {
	console.log('----- NEW CHUNK ----');
    console.log(chunk/toString());
	writeStream.write('\nNEW CHUNK\n');
    writeStream.write(chunk);
})

//pipe: pass data from readable to writable stream
//it must from readable one to writable one
readStream.pipe(writeStream);