在 NodeJs 中检查文件是否存在的最快方法 [英] Fastest way to check for existence of a file in NodeJs
问题描述
我正在节点和我的 onRequest 侦听器中构建一个超级简单的服务器,我试图根据中的路径确定是否应该提供静态文件(磁盘外)或一些 json(可能从 mongo 中提取)request.url
.
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
.
目前我正在尝试先统计文件(因为我在其他地方使用了 mtime),如果没有失败,那么我从磁盘读取内容.像这样:
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
}
});
除了为 request.url.pathname
缓存 fs.stat
的结果之外,还有什么可以加快这种检查的吗?例如,查看 fs.readFile
是否出错而不是 stat
是否同样快?或者使用 fs.createReadStream
而不是 fs.readFile
?或者我可以使用 child_process.spawn
中的内容检查文件吗?基本上,我只是想确保在应该将请求发送到 mongo 以获取数据时,我不会花费任何额外的时间来处理 fileio...
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...
谢谢!
推荐答案
var fs = require('fs');
fs.exists(file, function(exists) {
if (exists) {
// serve file
} else {
// mongodb
}
});
这篇关于在 NodeJs 中检查文件是否存在的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!