Skip to content

Commit

Permalink
Avoid emitting the 'error' event more than once.
Browse files Browse the repository at this point in the history
  • Loading branch information
papandreou committed May 28, 2014
1 parent b1ef5f5 commit 68a2c94
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/PngQuant.js
Expand Up @@ -23,20 +23,18 @@ function PngQuant(pngQuantArgs) {
this.hasEnded = false;
this.seenDataOnStdout = false;

this.pngQuantProcess.on('error', function (err) {
this.emit('error', err);
}.bind(this));
this.pngQuantProcess.on('error', this._reportError.bind(this));

this.pngQuantProcess.stderr.on('data', function (data) {
if (!this.hasEnded) {
this.emit('error', new Error('Saw pngquant output on stderr: ' + data.toString('ascii')));
this._reportError(new Error('Saw pngquant output on stderr: ' + data.toString('ascii')));
this.hasEnded = true;
}
}.bind(this));

this.pngQuantProcess.on('exit', function (exitCode) {
if (exitCode > 0 && !this.hasEnded) {
this.emit('error', new Error('The pngquant process exited with a non-zero exit code: ' + exitCode));
this._reportError(new Error('The pngquant process exited with a non-zero exit code: ' + exitCode));
this.hasEnded = true;
}
}.bind(this));
Expand All @@ -49,7 +47,7 @@ function PngQuant(pngQuantArgs) {
if (this.seenDataOnStdout) {
this.emit('end');
} else {
this.emit('error', new Error('PngQuant: The stdout stream ended without emitting any data'));
this._reportError(new Error('PngQuant: The stdout stream ended without emitting any data'));
}
this.hasEnded = true;
}
Expand All @@ -58,6 +56,13 @@ function PngQuant(pngQuantArgs) {

util.inherits(PngQuant, Stream);

PngQuant.prototype._reportError = function (err) {
if (!this.hasEnded) {
this.hasEnded = true;
this.emit('error', err);
}
};

PngQuant.prototype.write = function (chunk) {
this.pngQuantProcess.stdin.write(chunk);
};
Expand Down
21 changes: 21 additions & 0 deletions test/PngQuant.js
Expand Up @@ -64,4 +64,25 @@ describe('PngQuant', function () {

pngQuant.end(new Buffer('qwvopeqwovkqvwiejvq', 'utf-8'));
});

it('should emit a single error if an invalid command line is specified', function (done) {
var pngQuant = new PngQuant(['--blabla']),
seenError = false;

pngQuant.on('error', function (err) {
expect(pngQuant.commandLine, 'to match', /pngquant --blabla/);
if (seenError) {
done(new Error('More than one error event was emitted'));
} else {
seenError = true;
setTimeout(done, 100);
}
}).on('data', function (chunk) {
done(new Error('PngQuant emitted data when an error was expected'));
}).on('end', function (chunk) {
done(new Error('PngQuant emitted end when an error was expected'));
});

pngQuant.end(new Buffer('qwvopeqwovkqvwiejvq', 'utf-8'));
});
});

0 comments on commit 68a2c94

Please sign in to comment.