This repository has been archived by the owner on Jan 19, 2018. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.js
85 lines (75 loc) · 2.09 KB
/
index.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
var babel = require("babel-core");
var mkdirp = require("mkdirp");
var path = require("path");
var url = require("url");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (opts) {
opts = _.defaults(opts || {}, {
options: {},
dest: "cache",
src: "assets",
ignore: false
});
opts.ignore = babel.util.regexify(opts.ignore);
var cache = Object.create(null);
return function (req, res, next) {
if (opts.ignore.test(req.url)) return next();
if (!babel.util.canCompile(req.url)) return next();
var pathname = path.normalize(url.parse(req.url).pathname);
var dest = path.join(opts.dest, pathname);
var src = path.join(opts.src, pathname);
var srcStat;
var send = function (data) {
res.setHeader("Content-Type", "application/javascript");
res.end(data);
};
var write = function (transformed) {
mkdirp(path.dirname(dest), function (err) {
if (err) return next(err);
fs.writeFile(dest, transformed, function (err) {
if (err) {
next(err);
} else {
cache[pathname] = +srcStat.mtime;
send(transformed);
}
});
})
};
var compile = function () {
var transformOpts = _.clone(opts.options);
transformOpts.sourceFileName = "babel:///" + src.replace(opts.src, "");
babel.transformFile(src, transformOpts, function (err, result) {
if (err) {
next(err);
} else {
write(result.code);
}
});
};
var tryCache = function () {
fs.readFile(dest, function (err, data) {
if (err && err.code === "ENOENT") {
compile();
} else if (err) {
next(err);
} else {
send(data);
}
});
};
fs.stat(src, function (err, stat) {
srcStat = stat;
if (err && err.code === "ENOENT") {
next();
} else if (err) {
next(err);
} else if (cache[pathname] === +stat.mtime) {
tryCache();
} else {
compile();
}
});
};
};