node判断文件是否存在

问:

I'm building a super simple server in node and in my onRequest listener I'm trying to determine if I should serve a static file (off the disk) or some json (probably pulled from mongo) based on the path inrequest.url.

Currently I'm trying to stat the file first (because I use mtime elsewhere) and if that doesn't fail then I read the contents from disk. Something like this:

fs.stat(request.url.pathname, function(err, stat) {
    if (!err) {
        fs.readFile(request.url.pathname, function( err, contents) {
            //serve file
        });
    }else {
        //either pull data from mongo or serve 404 error
    }
});

Other than cacheing the result offs.statfor therequest.url.pathname, is there something that could speed this check up? For example, would it be just as fast to see iffs.readFileerrors out instead of thestat? Or usingfs.createReadStreaminstead offs.readFile? Or could I potentially check for the file using something inchild_process.spawn? Basically I just want to make sure I'm not spending any extra time messing w/ fileio when the request should be sent to mongo for data...

Thanks!

最佳答案

var fs = require('fs');

fs.exists(file, function(exists) {
  if (exists) {
    // serve file
  } else {
    // mongodb
  }
});



Please note thatfilecan actually be a directory, symlink, pipe, etc. To only find files, you could use something likefs.stat(file, function(err, stats) { if(!err && stats.isFile()) { //serve } else { //something else } });But even that doesn't guarantee that you can actually read that file. Permissions might be wrong, or the file might just be removed before you actually read it. Depending on the context, one way to approach the problem might be to just try reading the file and then do something else if it fails

其它答案

I don't think you should be worrying about that, but rather how can you improve the caching mechanism.fs.statis really ok for file checking, doing that in another child process would probably slow you down rather then help you here.

Connect implemented the staticCache() middleware a few months ago, as described in this blog post: http://tjholowaychuk.com/post/9682643240/connect-1-7-0-fast-static-file-memory-cache-and-more

A Least-Recently-Used (LRU) cache algo is implemented through theCacheobject, simply rotating cache objects as they are hit. This means that increasingly popular objects maintain their positions while others get shoved out of the stack and garbage collected.

Other resources:
http://senchalabs.github.com/connect/middleware-staticCache.html
The source code for staticCache

转载于:https://my.oschina.net/uniquejava/blog/227274

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值