command.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /**
  2. * Module dependencies.
  3. */
  4. var exec = require('child_process').exec;
  5. var spawn = require('child_process').spawn;
  6. var utils = require('./utils');
  7. var debug = require('debug')('gm');
  8. var series = require('array-series');
  9. var streamToBuffer = require('stream-to-buffer');
  10. /*
  11. * Creates a pass through stream.
  12. * We need to fallback to the `through` lib for node 0.8 support
  13. * as PassThrough was added in node 0.10.
  14. */
  15. var PassThrough = require('stream').PassThrough || require('through');
  16. /**
  17. * Error messaging.
  18. */
  19. var noBufferConcat = 'gm v1.9.0+ required node v0.8+. Please update your version of node, downgrade gm < 1.9, or do not use `bufferStream`.';
  20. /**
  21. * Extend proto
  22. */
  23. module.exports = function (proto) {
  24. function args (prop) {
  25. return function args () {
  26. var len = arguments.length;
  27. var a = [];
  28. var i = 0;
  29. for (; i < len; ++i) {
  30. a.push(arguments[i]);
  31. }
  32. this[prop] = this[prop].concat(a);
  33. return this;
  34. }
  35. }
  36. proto.in = args('_in');
  37. proto.out = args('_out');
  38. proto._preprocessor = [];
  39. proto.preprocessor = args('_preprocessor');
  40. /**
  41. * Execute the command and write the image to the specified file name.
  42. *
  43. * @param {String} name
  44. * @param {Function} callback
  45. * @return {Object} gm
  46. */
  47. proto.write = function write (name, callback) {
  48. if (!callback) callback = name, name = null;
  49. if ("function" !== typeof callback) {
  50. throw new TypeError("gm().write() expects a callback function")
  51. }
  52. if (!name) {
  53. return callback(TypeError("gm().write() expects a filename when writing new files"));
  54. }
  55. this.outname = name;
  56. var self = this;
  57. this._preprocess(function (err) {
  58. if (err) return callback(err);
  59. self._spawn(self.args(), true, callback);
  60. });
  61. }
  62. /**
  63. * Execute the command and return stdin and stderr
  64. * ReadableStreams providing the image data.
  65. * If no callback is passed, a "through" stream will be returned,
  66. * and stdout will be piped through, otherwise the error will be passed.
  67. *
  68. * @param {String} format (optional)
  69. * @param {Function} callback (optional)
  70. * @return {Stream}
  71. */
  72. proto.stream = function stream (format, callback) {
  73. if (!callback && typeof format === 'function') {
  74. callback = format;
  75. format = null;
  76. }
  77. var throughStream;
  78. if ("function" !== typeof callback) {
  79. throughStream = new PassThrough();
  80. callback = function (err, stdout, stderr) {
  81. if (err) throughStream.emit('error', err);
  82. else stdout.pipe(throughStream);
  83. }
  84. }
  85. if (format) {
  86. format = format.split('.').pop();
  87. this.outname = format + ":-";
  88. }
  89. var self = this;
  90. this._preprocess(function (err) {
  91. if (err) return callback(err);
  92. return self._spawn(self.args(), false, callback);
  93. });
  94. return throughStream || this;
  95. }
  96. /**
  97. * Convenience function for `proto.stream`.
  98. * Simply returns the buffer instead of the stream.
  99. *
  100. * @param {String} format (optional)
  101. * @param {Function} callback
  102. * @return {null}
  103. */
  104. proto.toBuffer = function toBuffer (format, callback) {
  105. if (!callback) callback = format, format = null;
  106. if ("function" !== typeof callback) {
  107. throw new Error('gm().toBuffer() expects a callback.');
  108. }
  109. return this.stream(format, function (err, stdout) {
  110. if (err) return callback(err);
  111. streamToBuffer(stdout, callback);
  112. })
  113. }
  114. /**
  115. * Run any preProcessor functions in series. Used by autoOrient.
  116. *
  117. * @param {Function} callback
  118. * @return {Object} gm
  119. */
  120. proto._preprocess = function _preprocess (callback) {
  121. series(this._preprocessor, this, callback);
  122. }
  123. /**
  124. * Execute the command, buffer input and output, return stdout and stderr buffers.
  125. *
  126. * @param {String} bin
  127. * @param {Array} args
  128. * @param {Function} callback
  129. * @return {Object} gm
  130. */
  131. proto._exec = function _exec (args, callback) {
  132. return this._spawn(args, true, callback);
  133. }
  134. /**
  135. * Execute the command with stdin, returning stdout and stderr streams or buffers.
  136. * @param {String} bin
  137. * @param {Array} args
  138. * @param {ReadableStream} stream
  139. * @param {Boolean} shouldBuffer
  140. * @param {Function} callback
  141. * @return {Object} gm
  142. * @TODO refactor this mess
  143. */
  144. proto._spawn = function _spawn (args, bufferOutput, callback) {
  145. var appPath = this._options.appPath || '';
  146. var bin = this._options.imageMagick
  147. ? appPath + args.shift()
  148. : 'gm'
  149. var proc = spawn(bin, args)
  150. , cmd = bin + ' ' + args.map(utils.escape).join(' ')
  151. , self = this
  152. , err;
  153. debug(cmd);
  154. if (self.sourceBuffer) {
  155. proc.stdin.write(this.sourceBuffer);
  156. proc.stdin.end();
  157. } else if (self.sourceStream) {
  158. if (!self.sourceStream.readable) {
  159. err = new Error("gm().stream() or gm().write() with a non-readable stream.");
  160. return cb(err);
  161. }
  162. self.sourceStream.pipe(proc.stdin);
  163. // bufferStream
  164. // We convert the input source from a stream to a buffer.
  165. if (self.bufferStream && !this._buffering) {
  166. if (!Buffer.concat) {
  167. throw new Error(noBufferConcat);
  168. }
  169. // Incase there are multiple processes in parallel,
  170. // we only need one
  171. self._buffering = true;
  172. streamToBuffer(self.sourceStream, function (err, buffer) {
  173. self.sourceBuffer = buffer;
  174. self.sourceStream = null; // The stream is now dead
  175. })
  176. }
  177. }
  178. // for _exec operations (identify() mostly), we also
  179. // need to buffer the output stream before returning
  180. if (bufferOutput) {
  181. var stdout = ''
  182. , stderr = ''
  183. , onOut
  184. , onErr
  185. , onExit
  186. proc.stdout.on('data', onOut = function (data) {
  187. stdout += data;
  188. });
  189. proc.stderr.on('data', onErr = function (data) {
  190. stderr += data;
  191. });
  192. proc.on('close', onExit = function (code, signal) {
  193. if (code !== 0 || signal !== null) {
  194. err = new Error('Command failed: ' + stderr);
  195. err.code = code;
  196. err.signal = signal;
  197. };
  198. cb(err, stdout, stderr, cmd);
  199. stdout = stderr = onOut = onErr = onExit = null;
  200. });
  201. proc.on('error', cb);
  202. } else {
  203. cb(null, proc.stdout, proc.stderr, cmd);
  204. }
  205. return self;
  206. function cb (err, stdout, stderr, cmd) {
  207. if (cb.called) return;
  208. cb.called = 1;
  209. if (args[0] !== 'identify' && bin !== 'identify') {
  210. self._in = [];
  211. self._out = [];
  212. }
  213. callback.call(self, err, stdout, stderr, cmd);
  214. }
  215. }
  216. /**
  217. * Returns arguments to be used in the command.
  218. *
  219. * @return {Array}
  220. */
  221. proto.args = function args () {
  222. var outname = this.outname || "-";
  223. if (this._outputFormat) outname = this._outputFormat + ':' + outname;
  224. return [].concat(
  225. this._subCommand
  226. , this._in
  227. , this.src()
  228. , this._out
  229. , outname
  230. ).filter(Boolean); // remove falsey
  231. }
  232. /**
  233. * Adds an img source formatter.
  234. *
  235. * `formatters` are passed an array of images which will be
  236. * used as 'input' images for the command. Useful for methods
  237. * like `.append()` where multiple source images may be used.
  238. *
  239. * @param {Function} formatter
  240. * @return {gm} this
  241. */
  242. proto.addSrcFormatter = function addSrcFormatter (formatter) {
  243. if ('function' != typeof formatter)
  244. throw new TypeError('sourceFormatter must be a function');
  245. this._sourceFormatters || (this._sourceFormatters = []);
  246. this._sourceFormatters.push(formatter);
  247. return this;
  248. }
  249. /**
  250. * Applies all _sourceFormatters
  251. *
  252. * @return {Array}
  253. */
  254. proto.src = function src () {
  255. var arr = [];
  256. for (var i = 0; i < this._sourceFormatters.length; ++i) {
  257. this._sourceFormatters[i].call(this, arr);
  258. }
  259. return arr;
  260. }
  261. /**
  262. * Image types.
  263. */
  264. var types = {
  265. 'jpg': /\.jpe?g$/i
  266. , 'png' : /\.png$/i
  267. , 'gif' : /\.gif$/i
  268. , 'tiff': /\.tif?f$/i
  269. , 'bmp' : /(?:\.bmp|\.dib)$/i
  270. , 'webp': /\.webp$/i
  271. };
  272. types.jpeg = types.jpg;
  273. types.tif = types.tiff;
  274. types.dib = types.bmp;
  275. /**
  276. * Determine the type of source image.
  277. *
  278. * @param {String} type
  279. * @return {Boolean}
  280. * @example
  281. * if (this.inputIs('png')) ...
  282. */
  283. proto.inputIs = function inputIs (type) {
  284. if (!type) return false;
  285. var rgx = types[type];
  286. if (!rgx) {
  287. if ('.' !== type[0]) type = '.' + type;
  288. rgx = new RegExp('\\' + type + '$', 'i');
  289. }
  290. return rgx.test(this.source);
  291. }
  292. }