-
Notifications
You must be signed in to change notification settings - Fork 11
/
static.js
31 lines (22 loc) · 864 Bytes
/
static.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
// static.js
//
// Packt Publishing - Build a Network Application with Node
// Serve static image files
var errUtil = require("err_util"),
path = require("path"),
fs = require("fs"),
mime = require("mime");
module.exports = function(req, res) {
var filePath = path.normalize("." + req.url),
contentType = mime.lookup(filePath);
fs.stat(filePath, function(err, stats) {
if (typeof stats == "undefined") return errUtil.report(null, res, 404, "File not found: " + filePath);
if (err) return errUtil.report(err, res);
if (stats.isDirectory() || !/image\/(jpeg|gif|png)/.test(contentType)) return errUtil.report(null, res, 403, "Forbidden");
fs.readFile(filePath, function(err, data) {
if (err) return errUtil.report(err, res);
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
});
};