node.js - Cache Image to Filesystem and Pipe Image to Response node.js - Cache Image to Filesystem and Pipe Image to Response express express

node.js - Cache Image to Filesystem and Pipe Image to Response


You can use a ThroughStream to accomplish this without having to wait for the entire file to be written to your file system. This works because the ThroughStream will internally buffer the data being piped into it.

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);        }    })}