![](/img/trans.png)
[英]Fastest way to check for an object's existence in a list in JavaScript
[英]Fastest way to check for existence of a file in NodeJs
我正在节点中构建一个超级简单的服务器,并在我的onRequest侦听器中尝试根据request.url
的路径确定是否应提供静态文件(磁盘外)或某些json(可能是从mongo提取)。 。
目前,我正在尝试首先对文件进行统计(因为我在其他地方使用了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
}
});
除了为request.url.pathname
缓存fs.stat
的结果fs.stat
,还有什么可以加快此检查速度的吗? 例如,查看fs.readFile
是否fs.readFile
错误而不是stat
一样快吗? 还是使用fs.createReadStream
代替fs.readFile
? 或者我是否可以使用child_process.spawn
检查文件? 基本上我只是想确保当请求应该发送到mongo来获取数据时,我不会花费任何额外的时间弄乱w / fileio ...
谢谢!
var fs = require('fs');
fs.exists(file, function(exists) {
if (exists) {
// serve file
} else {
// mongodb
}
});
此代码段可以帮助您
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
}
} );
我不认为您应该为此担心,而应该如何改善缓存机制。 fs.stat
确实可以进行文件检查,在另一个子进程中执行此操作可能会使您的速度变慢,但在此没有帮助。
如本博客文章所述,Connect几个月前实现了staticCache()中间件: http : //tjholowaychuk.com/post/9682643240/connect-1-7-0-fast-static-file-memory-cache-and -更多
最近最少使用(LRU)缓存算法是通过
Cache
对象实现的,只需在Cache
对象命中时旋转它们即可。 这意味着越来越受欢迎的对象将保持其位置,而其他对象则被推出堆栈并收集垃圾。
其他资源:
http://senchalabs.github.com/connect/middleware-staticCache.html
staticCache的源代码
如果您想使用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);
如果该文件不存在,它将转到将自身发送给自己的错误。 我在这里做了一个github回购https://github.com/dmastag/ex_fs/blob/master/index.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.