Created
February 18, 2013 22:52
-
-
Save geek0x23/4981505 to your computer and use it in GitHub Desktop.
browserify middleware with a file whitelist and very rudamentary caching.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var browserify = require("browserify"), | |
b = browserify(), | |
bundles = []; | |
module.exports = { | |
browserify: function(app) { | |
return function(req, res, next) { | |
// whitelist what we bundle. | |
var body, fileName, | |
isWhitelisted = false, | |
whitelist = ["customer.js"]; | |
// make sure that it's a validator url, and that we | |
// the requested path is whitelisted. this is just | |
// a simple means of protecting against directory | |
// traversal attacks and exposing application logic. | |
if (req.url.indexOf("/validators/") === 0) { | |
var counter = 0; | |
fileName = req.url.substring("12"); | |
for (counter = 0; counter < whitelist.length; counter += 1) { | |
if (fileName === whitelist[counter]) { | |
isWhitelisted = true; | |
break; | |
} | |
} | |
if (isWhitelisted === true) { | |
// check our cache first | |
if (app.enabled("browserifyCaching") && bundles[fileName]) { | |
body = bundles[fileName]; | |
} else { | |
// no cache entry, so bundle this and create one. | |
body = bundles[fileName] = b.require("./validators/" + fileName).bundle(); | |
} | |
res.setHeader("Content-Type", "application/javascript"); | |
res.setHeader("Content-Length", body.length); | |
res.end(body); | |
} else { | |
next(); | |
} | |
} else { | |
next(); | |
} | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
replace for loop with