如何加速node.js文件操作?
在我的项目中,客户端会请求从服务器下载一个带有ID的文件。 我必须执行以下操作:
- 从mongoDbvalidationID
- 检查扩展名
- 检查文件是否存在
- 阅读文件并将内容写入回复
我正在使用下面的代码来检查文件并发送响应。
fs.exists(filename, function(exists) { if (!exists) { res.writeHead(404, '', { "Content-Type" : "text/plain" }) res.write("404 Not Found\n"); res.end(); return; } fs.readFile(filename, "binary", function(err, file) { if (err) { res.writeHead(500, '', { "Content-Type" : "text/plain" }) res.write(err + "\n"); res.end(); return; } res.setHeader("Pragma", "public"); res.setHeader("Cache-Control: private, max-age=3600"); res.setHeader("Transfer-Encoding: chunked"); res.setHeader("Range: chunked"); res.writeHead(200, '', { "Content-Type" : contentType }); res.write(file, "binary"); res.end(file, "binary"); }); });
在几毫秒内,客户端将请求数百个文件。 支持的文件types是图像,audio或video。
当文件夹中有很多文件时,node.js文件的下载时间太长。 我该如何改善performance?
我会推荐几件事情。
-
你不应该使用
'binary'
。 根本不要给编码。 通过添加编码,您正在使节点做了大量额外的工作,将文件的Buffer
对象转换为二进制编码的string
。 当你用'binary'
再次调用write
时,意味着节点必须反向执行相同的操作。 另外,您还将文件传递到end
和write
,这意味着您下载的每个文件都将包含文件数据两次。 -
我build议不要使用
readFile
。 由于readFile
将整个文件内容传回给你的file
variables,所以你需要节点把文件的全部内容加载到RAM中,这意味着它需要分配大量的缓冲区,然后连接它们,这是不必要的工作。 -
没有理由分开使用
exists
,因为如果你尝试打开一个不存在的文件,错误会告诉你,所以首先检查只是额外的工作。
此外, Transfer-encoding
头部将被自行设置,您不需要这样做。
像这样的东西应该更快:
fs.createReadStream(filename) .on('error', function(err){ if (err.code === 'ENOENT'){ res.writeHead(404, { 'Content-type': 'text/plain' }); res.end('404 Not Found\n'); } else { res.writeHead(500, { 'Content-type': 'text/plain' }); res.end(err + '\n'); } }) .on('open', function(){ res.writeHead(200, { 'Pragma': 'public', 'Cache-Control': 'private, max-age=3600', 'Content-type': contentType }); }) .pipe(res);