在 NodeJs 中检查文件是否存在的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8782908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to check for existence of a file in NodeJs
提问by Lite Byte
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.
我正在节点和我的 onRequest 侦听器中构建一个超级简单的服务器,我试图根据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:
目前我正在尝试先统计文件(因为我在其他地方使用了 mtime),如果没有失败,那么我从磁盘读取内容。像这样的东西:
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.statfor 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.readFileerrors out instead of the stat? Or using fs.createReadStreaminstead 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...
除了缓存fs.statfor的结果之外request.url.pathname,还有什么可以加快此检查的速度吗?例如,查看是否fs.readFile出现错误而不是stat? 或者使用fs.createReadStream代替fs.readFile?或者我可以使用child_process.spawn. 基本上我只是想确保当请求应该发送到 mongo 以获取数据时,我不会花费任何额外的时间来弄乱文件...
Thanks!
谢谢!
回答by fent
var fs = require('fs');
fs.exists(file, function(exists) {
if (exists) {
// serve file
} else {
// mongodb
}
});
回答by alessioalex
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.
我不认为您应该担心这一点,而是您应该如何改进缓存机制。fs.stat对于文件检查来说真的没问题,在另一个子进程中这样做可能会减慢你的速度,而不是在这里帮助你。
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
Connect 几个月前实现了 staticCache() 中间件,如本博文所述:http: //tjholowaychuk.com/post/9682643240/connect-1-7-0-fast-static-file-memory-cache-and -更多的
A Least-Recently-Used (LRU) cache algo is implemented through the
Cacheobject, 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.
最近最少使用 (LRU) 缓存算法是通过
Cache对象实现的 ,只需在缓存对象被命中时对其进行轮换。这意味着越来越流行的对象会保持它们的位置,而其他对象会被推出堆栈并被垃圾收集。
Other resources:
http://senchalabs.github.com/connect/middleware-staticCache.html
The source code for staticCache
其他资源:
http
://senchalabs.github.com/connect/middleware-staticCache.html staticCache 的源代码
回答by Salar
this snippet can help you
这个片段可以帮助你
fs = require('fs') ;
var path = 'sth' ;
fs.stat(path, function(err, stat) {
if (err) {
if ('ENOENT' == err.code) {
//file did'nt exist so for example send 404 to client
} else {
//it is a server error so for example send 500 to client
}
} else {
//every thing was ok so for example you can read it and send it to client
}
} );
回答by julianalimin
In case you want to serve a file using express, I would recommend to just use the sendFile error Handler of express
如果您想使用 express 提供文件,我建议只使用 express 的 sendFile 错误处理程序
const app = require("express")();
const options = {};
options.root = process.cwd();
var sendFiles = function(res, files) {
res.sendFile(files.shift(), options, function(err) {
if (err) {
console.log(err);
console.log(files);
if(files.length === 0) {
res.status(err.status).end();
} else {
sendFiles(res, files)
}
} else {
console.log("Image Sent");
}
});
};
app.get("/getPictures", function(req, res, next) {
const files = [
"file-does-not-exist.jpg",
"file-does-not-exist-also.jpg",
"file-exists.jpg",
"file-does-not-exist.jpg"
];
sendFiles(res, files);
});
app.listen(8080);
If the file is not existent then it will go to the error that sends it self. I made a github repo here https://github.com/dmastag/ex_fs/blob/master/index.js
如果该文件不存在,那么它将转到自行发送的错误。我在这里做了一个 github 仓库https://github.com/dmastag/ex_fs/blob/master/index.js

