UNPKG

2.83 kBJavaScriptView Raw
1'use strict';
2
3var fs = require('fs-extra');
4var mode = require('stat-mode');
5var Ware = require('ware');
6
7/**
8 * Initialize Imagemin
9 *
10 * @api public
11 */
12
13function Imagemin() {
14 this.ware = new Ware();
15}
16
17/**
18 * Add a plugin to the middleware stack
19 *
20 * @param {Function} plugin
21 * @api public
22 */
23
24Imagemin.prototype.use = function (plugin) {
25 this.ware.use(plugin);
26 return this;
27};
28
29/**
30 * Get or set the source file
31 *
32 * @param {String|Buffer} file
33 * @api public
34 */
35
36Imagemin.prototype.src = function (file) {
37 if (!arguments.length) {
38 return this._src;
39 }
40
41 this._src = file;
42 return this;
43};
44
45/**
46 * Get or set the destination file
47 *
48 * @param {String} file
49 * @api public
50 */
51
52Imagemin.prototype.dest = function (file) {
53 if (!arguments.length) {
54 return this._dest;
55 }
56
57 this._dest = file;
58 return this;
59};
60
61/**
62 * Optimize file
63 *
64 * @param {Function} cb
65 * @api public
66 */
67
68Imagemin.prototype.optimize = function (cb) {
69 cb = cb || function () {};
70 var self = this;
71
72 this.read(function (err, file) {
73 self.run(file, function (err, file) {
74 if (err) {
75 return cb(err);
76 }
77
78 self.write(file, function (err) {
79 cb(err, file);
80 });
81 });
82 });
83};
84
85/**
86 * Run a file through the middleware
87 *
88 * @param {Array} file
89 * @param {Function} cb
90 * @api public
91 */
92
93Imagemin.prototype.run = function (file, cb) {
94 this.ware.run(file, this, cb);
95};
96
97/**
98 * Read the source file
99 *
100 * @param {Function} cb
101 * @api public
102 */
103
104Imagemin.prototype.read = function (cb) {
105 var file = {};
106 var src = this.src();
107
108 if (Buffer.isBuffer(src)) {
109 file.contents = src;
110 file.origSize = src.length;
111
112 return cb(null, file);
113 }
114
115 fs.stat(src, function (err, stats) {
116 if (err) {
117 return cb(err);
118 }
119
120 fs.readFile(src, function (err, buf) {
121 if (err) {
122 return cb(err);
123 }
124
125 file.contents = buf;
126 file.mode = mode(stats).toOctal();
127 file.origSize = buf.length;
128
129 cb(null, file);
130 });
131 });
132};
133
134/**
135 * Write file to destination
136 *
137 * @param {Object} file
138 * @param {Function} cb
139 * @api public
140 */
141
142Imagemin.prototype.write = function (file, cb) {
143 var dest = this.dest();
144
145 file.destSize = file.contents.length;
146
147 if (!dest) {
148 return cb();
149 }
150
151 fs.outputFile(dest, file.contents, function (err) {
152 cb(err);
153 });
154};
155
156/**
157 * Module exports
158 */
159
160module.exports = Imagemin;
161module.exports.gifsicle = require('./plugins/gifsicle');
162module.exports.jpegtran = require('./plugins/jpegtran');
163module.exports.optipng = require('./plugins/optipng');
164module.exports.pngquant = require('./plugins/pngquant');