Node.js / Express : download file via ajax

I am trying to dynamically request a file for download via a GET ajax call. I have the following client-side code:

$(function() {
    $('#submit').click(function() {
        $.ajax({
            type: "GET",
            url: "/download/" + "filename",
            dataType: "json",
            contentType: "application/json",
            complete: function() {
                console.log('Complete');
            },
            success: function() {
                console.log('Success');
            },
            error: function() {
                console.log('Error');
            }
        });
    });
});

On the node server I also have the following line (mind you, I have no idea if this is the correct way to do this)

app.get('/download/:filename', function(req, res) {
    console.log(req.params);
    res.write(fs.readFileSync(__dirname + "/../public/javascripts/main.js", 'utf8'));
});

So I want to actually download that javascript file (eventually dynamically). How would I go about doing this correctly? Something tells me I need to be specifying the headers / content type.

You should return with the content type and disposition set to:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"main.js\"

I believe you'll have to redirect to this file though. If I'm not mistaken, you can't force a file download via an AJAX call.

Is your intent to have the .js file interpreted and applied to the downloading page?

If so you would probably end up using write() to page, no matter how you GET it, and this would not be best-practice.

Instead check out require.js. This is a better way to asynchronously and dynamically load scripts, and apply them at runtime.

One difficulty that you would encounter in downloading dynamic .js files, with a manual solution, is dependencies. On .js file dependent on another would result in blind js undefined errors.

Plus, there is a runtime performance optimization gain in converting synchronous included files to asynchronous included files.

Require.js solves for these nicely.

Hope that helps. All the best! Clint