title: Node.js + request - saving a remote file and serving it in a response
body: <p>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)</p>
  
  <p>something like:</p>
  
  <pre><code>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);
  })
  </code></pre>
  
  <p>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 <code>fs.exists()</code> to check it exists first.</p>
  
  <hr>
  
  <p>This is my best effort so far:</p>
  
  <pre><code>http.createServer(function(req, res) {
      var file = fs.createWriteStream(local);
      request.get(remote).pipe(file).on('close', function() {
          res.end(fs.readFileSync(local), 'binary');
      });
  })
  </code></pre>