nodejs createReadStream empty file

Viewed 2285

I tried this simply code

var fs = require('fs');
var stream = fs.createReadStream(fileName);
stream.on('readable', function () {
   console.log("readable event called");
} );

And I noticed that if the file is an empty, then the event is not called. Is there elegant way to check that the file is empty?

1 Answers

You can use streamName.on('end', () => {})

let readStream = fs.createReadStream(path/to/file);
let emptyFile = true;

readStream.once('data', chunk => {
  emptyFile = false;
});

readStream.on('end', () => {
  console.log('Stream ended');
  if (emptyFile) {
    console.log('Empty file');
  }
});
Related