nodejs createReadStream空文件

时间:2016-03-10 14:31:14

标签: node.js fs

我试过这个简单的代码

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

我注意到如果文件为空,则不会调用该事件。是否有优雅的方法来检查文件是否为空?

1 个答案:

答案 0 :(得分:0)

您可以使用streamName.on('end', () => {})

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

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

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