I understand how to load a remote file with Node.js + request, and I can then read it and return the png binary blob. Is there a elegant way to do it with one request (or even a one-liner)
something like:
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png'
});
var picWrite = fs.createWriteStream(local);
var picFetch = fs.createReadStream(local);
picStream.on('close', function() {
console.log("file loaded");
});
request(remote).pipe(picWrite).pipe(picFetch).pipe(res);
})
To be clear: my aim is to load a remote file from a CDN, cache it locally to the server and then return the file in the original request. In future requests I use fs.exists()
to check it exists first.
This is my best effort so far:
http.createServer(function(req, res) {
var file = fs.createWriteStream(local);
request.get(remote).pipe(file).on('close', function() {
res.end(fs.readFileSync(local), 'binary');
});
})