My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Upload HTML file to AWS S3 and then serving it instead of downloading

Argjend's photo
Argjend
·Aug 25, 2017

Here is my concern:

I am downloading a webpage and then I am writing to a file named thisArticle.html

var file = fs.createWriteStream("thisArticle.html"); var request = http.get(req.body.url, function (response) { response.pipe(file); });

After that I am trying to read file and uploading to S3, here is the code that I wrote:


fs.readFile('thisArticle.html', 'utf8', function(err, html){

  if (err) { 
    console.log(err + "");
    throw err; 
  }

  var pathToSave = 'articles/ ' + req.body.title +'.html';

  var s3bucket = new AWS.S3({ params: { Bucket: 'all-articles' } });

  s3bucket.createBucket(function () {
    var params = {
      Key: pathToSave,
      Body: html,
      ACL: 'public-read'
    };

    s3bucket.upload(params, function (err, data) {

      fs.unlink("thisArticle.html", function (err) {
        console.error(err);
      });

      if (err) {
        console.log('ERROR MSG: ', err);
        res.status(500).send(err);
      } else { 
        console.log(data.Location);
      }

      // ..., more code below

    });

  });

});

Now, I am facing two issues:

  1. The file is uploading but with 0 bytes (empty)
  2. When I am trying to upload manually via S3 dashboard is uploaded successfully but when I tried to load the URL in the browser it downloads the html file instead of serving it.

Any guides if I am missing something ?