How to Safely Generate HTML Files in Node.js Using escape-html

aman pareek author
Aman Pareek

Published 30/10/2024

Updated 01/11/2024

I needed to generate an HTML file for my website, but I encountered the challenge of needing to escape certain code snippets. After searching for two days, I finally found the solution!

What Is Character Escaping and Why Is It Important?

Character escaping is the process of converting characters that have special meanings in HTML (like <, >, and &) into their corresponding HTML entities (like &lt;, &gt;, and &amp;). This is crucial because if we directly write code snippets into HTML, the browser will render them as actual HTML rather than display them as code. By escaping these characters, we can safely display code snippets within <pre> and <code> tags without risking unintended execution or display issues.

How to Escape HTML and Generate Files Safely

To escape HTML and generate files safely, we can use the wonderful escape-html package. Here’s how to get started:

Step 1: Install the Package

First, install the escape-html package in your Node.js project:

Shell

            npm i escape-html
        

Step 2: Write Your Code

Now, you can use the package to escape the code snippets you want to include in your HTML. Below is an example of how to do this:

index.js

            const escapeHtml = require('escape-html');
const fs = require('fs');

// Sample function code to be escaped
const functionCode = `function factorialIterative(number) {
  if (number < 0) {
      throw new Error("Factorial cannot be calculated for negative values.");
  }
  let product = 1;
  for (let i = 2; i <= number; i++) {
      product *= i;
  }
  return product;
} 

const n1 = 5;
console.log(factorialIterative(n1));  // Output: 120 

const n2 = 22;
console.log(factorialIterative(n2));  // Output: 1124000727777607680000`;

// Escape the function code for safe HTML output
const escapedHtml = escapeHtml(functionCode);

// Prepare the safe HTML content with proper structure
const safeHtml = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Safe HTML Output</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
        }
        pre {
            background-color: #f4f4f4;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <h1>Escaped Function Code</h1>
    <pre><code>${escapedHtml}</code></pre>
</body>
</html>
`;

// Write the safe HTML content to index.html with UTF-8 encoding
fs.writeFile('index.html', safeHtml, { encoding: 'utf8' }, (err) => {
  if (err) {
    console.error('Error writing to file:', err);
  } else {
    console.log('index.html has been created with the escaped function code!');
  }
});

        

Step 3: Run the Code

Now you can run this code from your terminal or shell to generate the HTML file safely.

Example Output: index.html

Here’s how the generated index.html file will look:

index.html

            <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Safe HTML Output</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
        }
        pre {
            background-color: #f4f4f4;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <h1>Escaped Function Code</h1>
    <pre><code>function factorialIterative(number) {
  if (number &lt; 0) {
      throw new Error(&quot;Factorial cannot be calculated for negative values.&quot;);
  }
  let product = 1;
  for (let i = 2; i &lt;= number; i++) {
      product *= i;
  }
  return product;
} 

const n1 = 5;
console.log(factorialIterative(n1));  // Output: 120 

const n2 = 22;
console.log(factorialIterative(n2));  // Output: 1124000727777607680000</code></pre>
</body>
</html>

        

With this approach, you can safely generate HTML files while preserving code snippets in a readable format. You can even play around with the code on platforms like StackBlitz!