title: Serving Temporary Files with NodeJs
body: <p>I am building a NodeJs SOAP client.  Originally, I imagined the server (ie the node SOAP client) would allow downloading documents through a REST API (the REST API is authenticated).  After a good deal of time on Google and SO, looks like that is not possible.</p>
  
  <p>That means when a document download is requested, I'll have to make a SOAP call for the document and return a URL to the REST client via AJAX. </p>
  
  <p>In order to do this I'll need to:</p>
  
  <ol>
  <li>Temporarily create a file in Node</li>
  <li>get its URL and return to web client</li>
  <li>When the file is requested and response is sent, delete the file (for security purposes)</li>
  </ol>
  
  <p>Here are my questions:</p>
  
  <ol>
  <li>Is there already a framework that does this?  the <a href="https://github.com/bruce/node-temp/blob/master/lib/temp.js" rel="noreferrer">temp module</a> might be an option, but really I'd like to delete after every request, not after a time period.</li>
  <li><p>If not, can I do this just using the NodeJs File System, and Express <a href="http://www.senchalabs.org/connect/static.html" rel="noreferrer">static module</a>?  Basically we would modify the static module to look like this:</p>
  
  <pre><code>return function static(req, res, next) {
    if ('GET' != req.method &amp;&amp; 'HEAD' != req.method) return next();
    var path = parse(req).pathname;
    var pause = utils.pause(req);
  
  /* My Added Code Here */
  res.on('end', function(){
      //  delete file based on req URL
  })
  /* end additions */
  
  function resume() {
    next();
    pause.resume();
  }
  
  function directory() {
    if (!redirect) return resume();
    var pathname = url.parse(req.originalUrl).pathname;
    res.statusCode = 301;
    res.setHeader('Location', pathname + '/');
    res.end('Redirecting to ' + utils.escape(pathname) + '/');
  }
  function error(err) {
     if (404 == err.status) return resume();
    next(err);
  }
  send(req, path)
    .maxage(options.maxAge || 0)
    .root(root)
    .hidden(options.hidden)
    .on('error', error)
    .on('directory', directory)
    .pipe(res);
  };
  </code></pre></li>
  </ol>
  
  <p>Is <code>res.on('end',...</code> vaild?  Alternatively,should I create some middleware that does this for URLs pointing to the temporary files?</p>