Karl Bateman Karl Bateman - 1 year ago 82
HTTP Question

HTTP requests until header has attachment

We have a web application which upon visiting the url, will prepare and generate a

file which is then downloaded.

I need to create a nodejs application using
that can keep making requests until there is an attachment header, from which point it would be downloaded.

The page which generates the
file contains a simple html message, stating that the file is being prepared for download. With a javascript
function called on load.

I'm not sure if this is the right way of doing it, but I am open to suggestions.

Answer Source

You could use async.until to loop through some logic until the header is available:

let success = true;
    // Do this as a test for each iteration
    function() {
        return success == true;
    // Function to loop through
    function(callback) {
        request(..., function(err, response, body) {
            // Header test
            if(resonse.headers['Content-Disposition'] == 'attatchment;filename=...') {
                success = true;
            // If you want to set a timeout delay
            // setTimeout(function() { callback(null) }, 3000);
    // Success!
    function(err) {
        // Do anything after it's done

You could do it with some other ways like a setInterval, but I would choose to use async for friendly asynchronous functionality.

EDIT: Here's another example using setTimeout (I didn't like the initial delay with setInterval.

let request = require('request');

let check_loop = () => {
    request('http://url-here.tld', (err, response, body) => {
        // Edit line below to look for specific header and value
        if(response.headers['{{HEADER_NAME_HERE}}'] == '{{EXPECTED_HEADER_VAL}}') 
            response.pipe(fs.createWriteStream('./filename.zip')); // write file to ./filename.zip
            // Not ready yet, try again in 30s
            setTimeout(check_loop, 30 * 1000);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download