-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-server.js
42 lines (34 loc) · 1.06 KB
/
file-server.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
'use strict';
var fsPath = require('path'),
fs = require('fs');
var mimetypes = {
'.js': 'application/javascript',
'.txt': 'text/plain'
};
var config = {};
function servePublicFile(httpReq, httpRes) {
var relativePath = httpReq.url.replace(config.basePathRe, ''),
path = fsPath.join(config.publicPath, relativePath);
fs.exists(path, function(ok) {
if (ok) {
var ext = fsPath.extname(path);
if (ext in mimetypes) {
httpRes.setHeader('Content-Type', mimetypes[ext]);
}
var stream = fs.createReadStream(path);
stream.pipe(httpRes);
} else {
var body = 'not found';
httpRes.writeHead(404, {
'Content-Length': body.length,
'Content-Type': 'text/plain'
});
httpRes.end(body);
}
});
}
servePublicFile.configure = function configure(mainConfig) {
config.publicPath = mainConfig.publicPath;
config.basePathRe = mainConfig.dataRe;
};
module.exports = servePublicFile;