Node.js: First Character is undefined in fs.createReadStream

807 views Asked by At

I am trying to read streams from a simple text file and logging all the characters once the Read Streams gets completed but strangely every time the first character is always undefined. I am not sure if I am missing anything while reading streams from text file.

`

const fs= require('fs');
const readStreams = fs.createReadStream('text.txt');
let data;
readStreams.on('data',(dataChunks)=>{
  data+=dataChunks;
}
);

readStreams.on('end',() =>{
    console.log(data);
});

` Terminal Screenshot

1

There are 1 answers

0
Sumeet Kumar Yadav On BEST ANSWER

You have initialized data with undefined that's getting appended to stream , assigning empty string will solve your problem

let data = '';

Alternate solution would be using pipe operation instead of data

readStreams.pipe(process.stdout);