Yujun Wu
Yujun Wu

Reputation: 3012

node write after end error when repeatedly stream read and write

Was using this lib to convert .pcm file to .mp3 file. Sometimes the converted mp3 file would be empty somehow, so wrote a retry mechanism to eliminate the issue:

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.`);
  }
}

It throws error Error: write after end when the retries happened and I don't not understand why.

Upvotes: 0

Views: 1201

Answers (1)

Kerstomaat
Kerstomaat

Reputation: 713

You should instantiate a new encoder on each retry

Upvotes: 1

Related Questions