Speed up development with full-stack environments for every branch.

Learn More

Download files with express [Node.js]

5229 Runs 30515 Views 7600 Copies
Saved

Saved

runnable 15

runnable
published 4 years ago

// http://expressjs.com/api.html#res.download
var express = require('express')
  , app = module.exports = express();
 
app.get('/', function(req, res){
  res.send('<ul>'
    + '<li>Download <a href="/amazing.txt">amazing.txt</a>.</li>'
    + '<li>Download <a href="/missing.txt">missing.txt</a>.</li>'
    + '</ul>');
});

// /files/* is accessed via req.params[0]
// but here we name it :file
app.get('/:file(*)', function(req, res, next){
  var file = req.params.file
    , path = __dirname + '/files/' + file;

  res.download(path);
});

// error handling middleware. Because it's
// below our routes, you will be able to
// "intercept" errors, otherwise Connect
// will respond with 500 "Internal Server Error".
app.use(function(err, req, res, next){
  // special-case 404s,
  // remember you could
  // render a 404 template here
  if (404 == err.status) {
    res.statusCode = 404;
    res.send('Cant find that file, sorry!');
  } else {
    next(err);
  }
});

if (!module.parent) {
  app.listen(80);
  console.log('Express started on port %d', 80);
}
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).