On Monday, September 15, 2014 9:28:28 AM UTC-7, Ingwie Phoenix wrote:
>
> Hai, everyone.
>
> So I just figured out that Connect’s static file servers dont work well
> with symlinks…so I had tow rite myself a little workaround, a fallback
> router, per-se. But whilst I did so, I had a nice meeting with the callback
> hell. Here’s my code:
>
> CDN.use(config.CDN.baseUrl, function(req, res, next){
> if(err) { next(); throw err; }
> fs.lstat(config.base+"/cdn"+req.url, function(err,stats){
> if(stats.isSymbolicLink()) {
> fs.readlink(config.base+"/cdn"+req.url,
> function(err, linkstr){
> if(err) throw err;
> log.info("Redirecting request \""+req.url+"\"
> to \""+linkstr);
> fs.readFile(linkstr, function(err, data){
> if(err) throw err;
>
> res.writeHead(200,{"Content-type":"text/html"});
> res.end(data);
> });
> });
> }
> });
> });
> });
>
>
Best way to not write callback hell: STOP WRITING IT.
CDN.use(config.CDN.baseUrl, require('cdn-middleware'));
cdn-middleware:
module.exports = function(req, res, next){
var path = config.base + "/cdn" + req.url;
fs.lstat(path, function(err,stats){
if(stats.isSymbolicLink()) {
serveLink();
} else {
return next();
}
});
function serveLink() {
fs.readlink(path, handleError(function(linkstr){
log.info <http://log.info>('Redirecting request "' + req.url +
'" to "' + linkstr + '"');
// This could probably be:
// res.statusCode(200);
// fs.createReadStream(linkstr).pipe(res);
fs.readFile(linkstr, handleError(data) {
res.writeHead(200,{"Content-type":"text/html"});
res.end(data);
});
});
}
function handleError(fn) {
return function (err, data) {
if (err) {
return next(err);
} else {
return fn(data);
}
}
}
});
> Okay…thats lots. And how does one get around this and into a bit of nicer
> code? It almost looks like a little pyramid there…
>
Name your functions. Move them as far left as you can (depending on how
many variables they share with the context).
Now that said, not playing nice with symlinks sounds like a bug: have you
opened an issue?
Aria
--
Job board: http://jobs.nodejs.org/
New group rules:
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/nodejs/0a92492a-beba-4dd7-bd75-889234a6cf26%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.