1

I am trying to save large amounts of HTML in JavaScript so that I can read it and replace some bits with custom text. I am not sure what's the best way to do this. I am working on a Serverless infrastructure, i.e. using Lamdba functions.

Any help would be greatly appreciated.

2
  • What do you mean "save HTML in Javascript"? You have a webpage and want to extract info and save it as JSON or something? What is the data of the HTML and Javascript you want to produce? Commented May 22, 2017 at 12:50
  • 1
    I would like to save a html file in the project and load it into a javascript variable so that I can change a few bits of it based on some logic. I want to ideally store these as mustacheJS templates or something similar to be processed in lambda functions. Commented May 22, 2017 at 12:54

2 Answers 2

1

You can server HTML pages using Lambda functions. You just need to set the headers.

See this example:

module.exports.landingPage = (event, context, callback) => {
  let dynamicHtml = '<p>Hey Unknown!</p>';
  // check for GET params and use if available
  if (event.queryStringParameters && event.queryStringParameters.name) {
    dynamicHtml = `<p>Hey ${event.queryStringParameters.name}!</p>`;
  }

  const html = `
  <html>
    <style>
      h1 { color: #73757d; }
    </style>
    <body>
      <h1>Landing Page</h1>
      ${dynamicHtml}
    </body>
  </html>`;

  const response = {
    statusCode: 200,
    headers: {
      'Content-Type': 'text/html',
    },
    body: html,
  };

  // callback is sending HTML back
  callback(null, response);
};

Or you could return a JSON object, as Lambda functions are commonly used, and this JSON object would have a HTML string set as one of the properties.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for! Worked for me
0

You can use a JavaScript based HTML templating library such as UnderscoreJS to compile and upload HTML templates in the form of JavaScript dependancies along with Lambda code.

This allows replacing parts in your HTML using placeholders which is easy to maintain.

3 Comments

I've been trying to do something like this using another templating engine - Nunjucks but for some reason, it can't find the directory that I've placed my HTML files in. Could you provide some sample code on how this can be done?
Did you check whether the file paths are correct?
The path was correct. I just had to figure out how to include my .html files in the build folder - stackoverflow.com/a/75075719/6644114

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.