Fastest way to check for existence of a file in NodeJs


Question

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 in request.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 of fs.stat for the request.url.pathname, is there something that could speed this check up? For example, would it be just as fast to see if fs.readFile errors out instead of the stat? Or using fs.createReadStream instead of fs.readFile? Or could I potentially check for the file using something in child_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!

1
34
1/9/2012 1:04:44 AM

var fs = require('fs');

fs.exists(file, function(exists) {
  if (exists) {
    // serve file
  } else {
    // mongodb
  }
});
58
10/7/2012 3:04:17 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon