Harkirat Saluja
Harkirat Saluja

Reputation: 8114

Reading from a file in node.js

I was just wondering if this code would work while reading from a file in node.js.

I am getting following error:-

"read() returned null, which resulted in a runtime error: Cannot read property 'toString' of null"

 var fs = require('fs');
 var file=fs.createReadStream('abc.txt');
 file.on('readable',function(){
         while( file.read() !== null)
         {
             console.log(file.read().toString());
         }
  });

Upvotes: 0

Views: 96

Answers (1)

prasun
prasun

Reputation: 7343

Calling file.read will advance the current pointer position in the stream object twice. During the last chunk read, the while condition gets true and file.read() returns null, which results in an error.

Try the code below:

data = file.read(); // Read first chunk
while (data !== null){
    console.log(data.toString());
    data = file.read(); // Read next chunk
}

Upvotes: 1

Related Questions