fs.read有不同的行为

时间:2017-01-10 12:43:01

标签: node.js

知道为什么fs.read不能表现为fs.readSync

我的代码非常简单,只需按块读出歌曲文件块。我发现使用fs.readSync函数,每次使用fs.read函数时歌曲文件可以读出512个字节,没有打印出日志信息,如果删除while(readPosition < fileSize),它会执行只有一次。

var chunkSize  = 512;   //the chunk size that will be read every time
var readPostion = 0;  //the first byte which will be read from the file.
var fileSize  =0;
var fs=require('fs');
//var Buffer = require("buffer");


//var songsBuf = Buffer.alloc(512);
var songsBuf = new Buffer(chunkSize);
fs.open('/media/sdcard/song.mp3','r',function(err,fd){
  if(err)
      throw err;
  console.log("The file had been opened");

  var fileSize = fs.fstatSync(fd).size;
  console.log("The total size of this file is:%d Bytes",fileSize);

  console.log("Start to read the file chunk by chunk");

  //read the file in sync mode 
  while(readPostion<fileSize)  
  {
      fs.readSync(fd,songsBuf,0,chunkSize,readPostion);
      if(readPostion+chunkSize>fileSize)
          chunkSize = fileSize-readPostion;
      readPostion+=chunkSize;
      console.log("the read position is %d",readPostion);
      console.log("The chunk size is %d",chunkSize);
      console.log(songsBuf);
  }
  //the code above can readout the file chunk by chunk but the below one cannot
  //read the file in Async mode.
  while(readPostion<fileSize)
  {   
   //   console.log("ff");
      fs.read(fd,songsBuf,0,chunkSize,1,function(err,byteNum,buffer){
        if(err)
          throw err;
        console.log("Start to read from %d byte",readPostion);
        console.log("Total bytes are %d",byteNum);
        console.log(buffer); 
        if(readPostion+chunkSize>fileSize)
           chunkSize = fileSize-readPostion; //if the files to read is smaller than one chunk   
        readPostion+=chunkSize;
      });   
  }

  fs.close(fd);
});

1 个答案:

答案 0 :(得分:0)

您可以使用async library

执行此操作
async.whilst(
  function () { return readPostion < fileSize },
  function (callback) {
    fs.read(fd, songsBuf, 0, chunkSize, 1, function (err, byteNum, buffer) {
      if (err) return callback(err)
      console.log("Start to read from %d byte",readPostion);
      console.log("Total bytes are %d",byteNum);
      console.log(buffer); 
      if(readPostion + chunkSize > fileSize)
        chunkSize = fileSize - readPostion; //if the files to read is smaller than one chunk   
      readPostion += chunkSize
      callback(null, songBuffer)
    })
  },
  function (err, n) {
    if (err) console.error(err)
    fs.close(fd)
    // Do something with songBuffer here
  }
)