Skip to content

Instantly share code, notes, and snippets.

@goje87

goje87/router.js Secret

Created January 27, 2014 17:57
Show Gist options
  • Save goje87/8aa5c04bf3b0f5de907d to your computer and use it in GitHub Desktop.
Save goje87/8aa5c04bf3b0f5de907d to your computer and use it in GitHub Desktop.
Serving static content in iron-router
var routerCounfiguration = {
layoutTemplate: 'mainLayout',
notFoundTemplate: 'notFoundTemplate'
};
Router.configure(routerCounfiguration);
Router.map(function() {
this.route('home', {
path: '/'
});
this.route('public', {
path: '/public/:path(*)',
where: 'server',
action: function() {
this.response.write('hello world');
}
});
});
@rand0mUser
Copy link

If it's still relevant, here's the code I use:
(notice that I use synchronous functions, so the code gets blocked every time a file is being read, so don't forget to adjust it to your needs as necessary)

Router.map(function() {
    this.route('downloadRoute', {
        path: '/download/:filename',
        where: 'server',

        action: function() {
            var filename = this.params.filename

            var fs = Npm.require('fs'),
                filePath = '/Users/userName/projectName/public/',
                response = this.response

        // Here you can check if the filename is correct:
            if (fileName === 'correctFileName') {
                // ...
            } else {
                return
            }

            var fileSize = fs.statSync(filePath)

            response.writeHead(200, {
                'Content-Type': 'application/zip',      // Change to the type of file you're serving
                'Content-Disposition': 'attachment; filename="' + fileName + '"',
                'Content-Size': fileSize
            })

            response.write(fs.readFileSync(filePath))
            response.end()
        }
    })
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment