Search code examples
node.jsnode-streams

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


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


Solution

  • 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);