-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcss-prefixer-middleware.js
67 lines (50 loc) · 1.6 KB
/
css-prefixer-middleware.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
// For options and giggles:
// https://github.com/ai/autoprefixer
var autoprefixer = require('autoprefixer');
var fs = require('fs');
var url = require('url');
var path = require('path');
var filesMap = {};
module.exports = function ( options ) {
options = options || {};
if (!options.src) { throw new Error('autoprefixer-mw requires "src" directory'); }
return function ( req, res, next ) {
var pathname = url.parse(req.url).pathname;
var filename = path.resolve( options.src + pathname );
// Skip if request is not GET or HEAD
if ('GET' !== req.method.toUpperCase() && 'HEAD' !== req.method.toUpperCase()) {
return next();
}
// Skip if request is not for a CSS file
if ( path.extname(pathname) !== '.css' ) {
return next();
}
filesMap[filename] = filesMap[filename] || {};
filesMap[filename].stats = filesMap[filename].stats || {};
fs.stat(filename, function ( err, stats ) {
if (err || !stats.isFile() || filesMap[filename].stats.mtime && stats.mtime.getTime() === filesMap[filename].stats.mtime.getTime() ) {
return next(err);
}
fs.readFile( filename, {encoding:'utf8'}, function ( err, css ) {
var prefixed;
try {
prefixed = autoprefixer( options.args ).process(css, options.options).css;
} catch ( error ) {
return next(err);
}
fs.writeFile( filename, prefixed, {encoding:'utf8'}, function ( err ) {
if (err) {
return next(err);
}
next();
fs.stat( filename, function ( err, stats ) {
if (err) {
return next(err);
}
filesMap[filename].stats = stats;
});
});
});
});
};
};