0
var content = 'Hi, welcome to my webpage.';
var options = {host: 'www.website.com', path: '/folder/song.mp3', agent:false};

http.get(options, function(r) {
  r.on('data', function() {
    if (r.statusCode !== '404') {
      content += '<a href="www.website.com/folder/song.mp3">Download</a>';
    }
  });
});

fs.writeFile('index.html', content);

So normally, if I want to write a static html webpage from a node.js script, this works perfectly. For some reason, however, if I try to append to content from within http.get, it doesn't work. The whole point is to check if the file/page exists from an external website, and if it does then to display a link to it. The code that checks for the existing file works just fine, but I can't append anything to an external variable it seems. Any help would be much appreciated.

1 Answer 1

1

You need to use end event of http to indicate when you finish receiving data. As node is asynchronouse the fs.writeFile instruction is run before all your data is received.

Here's how you can do it:

http.get(options, function(r) {
  r.on('data', function() {
    if (r.statusCode !== '404') {
      content += '<a href="#">Download</a>';
    }
  });
  r.on('end', function() {
     fs.writeFile('index.html', content);
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.