1 | 'use strict';
|
2 |
|
3 | var fs = require('fs-extra');
|
4 | var mode = require('stat-mode');
|
5 | var Ware = require('ware');
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | function Imagemin() {
|
14 | this.ware = new Ware();
|
15 | }
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | Imagemin.prototype.use = function (plugin) {
|
25 | this.ware.use(plugin);
|
26 | return this;
|
27 | };
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | Imagemin.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 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | Imagemin.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 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | Imagemin.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 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | Imagemin.prototype.run = function (file, cb) {
|
94 | this.ware.run(file, this, cb);
|
95 | };
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 | Imagemin.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 |
|
136 |
|
137 |
|
138 |
|
139 |
|
140 |
|
141 |
|
142 | Imagemin.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 |
|
158 |
|
159 |
|
160 | module.exports = Imagemin;
|
161 | module.exports.gifsicle = require('./plugins/gifsicle');
|
162 | module.exports.jpegtran = require('./plugins/jpegtran');
|
163 | module.exports.optipng = require('./plugins/optipng');
|
164 | module.exports.pngquant = require('./plugins/pngquant');
|