From a2dccd266098ad0fced9baa51a814da18942bfac Mon Sep 17 00:00:00 2001 From: Marc Bachmann Date: Tue, 14 Apr 2015 20:57:14 +0200 Subject: [PATCH] Add timeout support --- lib/command.js | 16 +++++++++++++++- test/timeout.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 test/timeout.js diff --git a/lib/command.js b/lib/command.js index 7a68ce9..63d2661 100644 --- a/lib/command.js +++ b/lib/command.js @@ -217,7 +217,9 @@ module.exports = function (proto) { var cmd = bin + ' ' + args.map(utils.escape).join(' ') , self = this - , proc, err; + , proc, err + , timeout = parseInt(this._options.timeout) + , timeoutId; debug(cmd); @@ -228,6 +230,17 @@ module.exports = function (proto) { } proc.stdin.once('error', cb); + if (timeout) { + timeoutId = setTimeout(function(){ + err = new Error('gm() resulted in a timeout.'); + cb(err); + if (proc.connected) { + proc.stdin.pause(); + proc.kill(); + } + }, timeout); + } + if (self.sourceBuffer) { proc.stdin.write(this.sourceBuffer); proc.stdin.end(); @@ -300,6 +313,7 @@ module.exports = function (proto) { function cb (err, stdout, stderr, cmd) { if (cb.called) return; + if (timeoutId) clearTimeout(timeoutId); cb.called = 1; if (args[0] !== 'identify' && bin !== 'identify') { self._in = []; diff --git a/test/timeout.js b/test/timeout.js new file mode 100644 index 0000000..a7e6e76 --- /dev/null +++ b/test/timeout.js @@ -0,0 +1,33 @@ + +var assert = require('assert') + +module.exports = function (img, dir, finish, gm) { + + assert.equal(undefined, gm.prototype._options.timeout); + assert.equal(undefined, img._options.timeout); + + var g = gm('test').options({ timeout: 100 }); + assert.equal(100, g._options.timeout); + + var sub = gm.subClass({ timeout: 2000 }); + assert.equal(2000, sub.prototype._options.timeout); + + + if (!gm.integration) + return finish(); + + gm(dir + '/photo.JPG').options({ timeout: 1 }) + .thumb(50, 80, dir + '/timeout.png', function subthumb (err) { + assert.ok(err, "Expecting a timeout error"); + noTimeout(); + }); + + + function noTimeout() { + gm(dir + '/photo.JPG').options({ timeout: 0 }) + .thumb(50, 80, dir + '/timeout.png', function subthumb (err) { + finish(err); + }); + } + +}