Deepak
Deepak

Reputation: 303

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

Upvotes: 0

Views: 840

Answers (1)

Sumeet Kumar Yadav
Sumeet Kumar Yadav

Reputation: 12975

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

Upvotes: 1

Related Questions