Node.js - 将图片缓存到文件系统并将图片传输到响应流

7
我的目标是构建一个简单的文件系统缓存系统,以减少我们调用 API 获取缩略图图像的次数。该过程是检查图像是否已经存在于文件系统中(使用fs.stat),如果不存在,则从 API 端点请求图像,并同时将图像写入文件系统。我希望我可以同时将请求传输到文件系统和响应中,但我不认为这是可能的,所以我首先将响应流传输到文件系统,然后创建一个流来将图像从文件系统传输到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://www.example.com/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);
            }
        })
    }
1个回答

12
您可以使用ThroughStream来完成此操作,而无需等待整个文件被写入您的文件系统。这是因为ThroughStream将在其内部缓冲数据被管道传输进来。
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://www.example.com/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);
        }
    })
}

正是我所需要的...一定要爱SO!谢谢。 - hotshotiguana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接