forked from saml/nodejs-resize-image
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
286 lines (248 loc) · 7.94 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
var http = require('http');
var fs = require('fs');
var sys = require('sys');
var path = require('path');
var child = require('child_process');
var util = require('./util');
var tempfile = require('./tempfile');
var settings = require('./settings');
//GET /path/to/image.c.120x64.jpg
//will execute
//convert scrDir/path/to/image.jpg \
// -size 120x64 destDir/image.c.120x64.jpg
//and serve destDir/path/to/image.c.120x64.jpg
var Server = function(convert, srcDir, destDir) {
var me = {};
var regex = /^\/(.+)\.c\.(\d+)x(\d+)(\.\w+)$/;
var parseUrl = function(url) {
var m = regex.exec(url);
if (!m) {
return null;
}
var ext = m[4];
var src = path.join(srcDir, '%s%s'.f(m[1], ext));
var out = path.join(destDir, tempfile.getName("", ext));
return {
width: m[2] * 1
, height: m[3] * 1
, src: src
, out: out
};
};
var getMimeType = function(name) {
var ext = path.extname(name).toLowerCase();
switch (ext) {
case '.jpg':
case '.jpeg':
return 'image/jpeg';
case '.png':
return 'image/png';
case '.gif':
return 'image/gif';
case '.tif':
case '.tiff':
return 'image/tiff';
}
return 'application/octet-stream';
};
//handles request.
var Handler = function(request, response) {
var me = {};
var serveFile = function(filePath, mimeType, callback) {
if (!mimeType) {
mimeType = getMimeType(filePath);
}
var encoding = 'binary';
fs.stat(filePath, function(err, stat) {
if (err || !stat.isFile()) {
me.do404();
return;
}
response.writeHead(200, {
'Content-Type': mimeType
, 'Content-Length': stat.size
});
var stream = fs.createReadStream(filePath, {
flags: 'r'
, encoding: encoding
});
stream.on('data', function(data) {
response.write(data, encoding);
});
stream.on('close', function() {
response.end();
if (typeof callback === 'function') {
callback();
}
});
stream.on('error', function(err) {
throw new Error('error reading file: ' + filePath);
});
});
};
var resizeImage = function(src, out, size, callback) {
var basePath = path.dirname(out);
var doResize = function() {
var args = [src, '-resize', size, out];
sys.log('executing: %s %s'.f(convert, args.join(' ')));
var p = child.spawn(convert, args);
p.on('exit', function(code) {
if (code === 0) {
if (typeof callback === 'function') {
callback(out);
}
} else {
throw new Error(
'convert %s exited with %s'.f(args.join(' '), code));
}
});
};
util.mkdirP(basePath, 0755, function(err) {
if (err) {
sys.log(err);
throw new Error('cannot create directory: ' + basePath);
} else {
doResize();
}
});
};
me.do404 = function(msg) {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
var data = 'Not Found: ' + request.url;
if (msg) {
data = '\n%s'.f(data);
}
response.end(data);
};
me.do500 = function(msg) {
response.writeHead(500, {
'Content-Type': 'text/plain'
});
var data = 'Internal Error: ' + request.url;
if (msg) {
data = '\n%s'.f(msg);
}
response.end(data);
};
me.do501 = function(msg) {
response.writeHead(501, {
'Content-Type': 'text/plain'
});
var data = 'Not Supported Method: %s %s'.f(request.method, request.url);
if (msg) {
data = '\n%s'.f(msg);
}
response.end(data);
};
me.start = function() {
if (request.method !== 'GET') {
me.do501();
return;
}
var o = parseUrl(request.url);
if (!o) {
sys.log('cannot parse: ' + request.url);
me.do404();
return;
}
var size = '%sx%s'.f(o.width, o.height);
resizeImage(o.src, o.out, size, function() {
serveFile(o.out, undefined, function() {
fs.unlink(o.out, function(err) {
if (err) {
sys.log('error while deleting: ' + o.out);
}
});
});
});
/*
path.exists(o.out, function(exists) {
if (exists) {
sys.log('serving from cache: ' + o.out);
serveFile(o.out);
} else {
sys.log('creating cache: ' + o.out);
var size = '%sx%s'.f(o.width, o.height);
resizeImage(o.src, o.out, size, function() {
serveFile(o.out);
});
}
});
*/
};
return me;
};
me.server = http.createServer(function(request, response) {
var handler = Handler(request, response);
try {
handler.start();
} catch (e) {
var msg = sys.inspect(e, true, null);
sys.log('error while handling %s %s'.f(request.url, e));
handler.do500();
}
});
me.server.on('close', function() {
sys.log('Server stopped');
});
me.start = function(host, port) {
me.stop();
me.server.listen(port, host, function() {
sys.log('Server started %s:%s'.f(host, port));
});
};
me.stop = function() {
try {
me.server.close();
} catch (e) {
}
};
return me;
};
var main = function() {
var argv = process.argv;
//if (argv.length < 3) {
// console.log("Usage: %s %s config.json".f(argv[0], argv[1]));
// process.exit(1);
//}
//
var port = settings.port || 8080;
var host = settings.host || '127.0.0.1';
var convert = settings.convert || 'convert';
var srcDir = settings.srcDir || './';
var destDir = settings.destDir || './tmp/';
var baseDir = process.cwd();//__dirname;
if (!srcDir.startsWith('/')) {
srcDir = path.join(baseDir, srcDir);
}
if (!destDir.startsWith('/')) {
destDir = path.join(baseDir, destDir);
}
if (argv.length > 2) {
var hostPort = argv[2];
var m = /([^:]+):(\d+)/.exec(hostPort);
if (m) {
host = m[1];
port = m[2] * 1.0;
}
}
console.log('Using\n'
+ '\thost\t%s\n'.f(host)
+ '\tport\t%s\n'.f(port)
+ '\tconvert\t%s\n'.f(convert)
+ '\tsrcDir\t%s\n'.f(srcDir)
+ '\tdestDir\t%s\n'.f(destDir))
var server = Server(convert, srcDir, destDir);
var exit = function() {
server.stop();
process.exit(0);
};
process.on('SIGINT', exit);
process.on('SIGTERM', exit);
process.on('SIGQUIT', exit);
process.on('SIGKILL', exit);
server.start(host, port);
};
main();