重复流读取和写入

时间:2016-01-25 23:44:22

标签: node.js

使用此lib将.pcm文件转换为.mp3文件。有时转换后的mp3文件会以某种方式为空,所以写了一个重试机制来消除这个问题:

const retriesLimit = 5,
      retryInterval = 5000;

function convert(inputPath, outputPath, retries) {
  return new Promise((resolve, reject) => {
    _convert(inputPath, outputPath, resolve, reject, retries);
  });
}

function _convert(inputPath, outputPath, resolve, reject, retries=0) {    
  if (retries <= retriesLimit) {
    let readStream = fs.createReadStream(inputPath),
        writeStream = fs.createWriteStream(outputPath);

    readStream.pipe(encoder);

    encoder.pipe(writeStream);

    readStream.on('end', () => {
      console.log('pcm read stream ended.');
    });

    readStream.on('error', err => reject(err));
    writeStream.on('error', err => reject(err));

    if (retries) {
      console.log(`Retry ${retries} times to convert pcm to mp3`);
    }

    writeStream.on('finish', () => {
      getFileSize(outputPath)
        .then(size => {
          console.log('Converted mp3 size:', size);
          if (size === 0) {
            setTimeout(() => {
              _convert(inputPath, outputPath, resolve, reject, retries + 1);
            }, retryInterval);
          } else {
            console.log('mp3 file created.');
            resolve(true);
          }
        });
    });
  } else {
    reject(`Converted mp3 file is empty. Retries ${retries} times.`);
  }
}

重试发生时抛出错误Error: write after end,我不明白为什么。

1 个答案:

答案 0 :(得分:1)

您应该在每次重试

时实例化一个新的encoder