#web development
#programming
#nodejs

How to Create a Html Files in Node.js?

Anonymous

AnonymousOct 07, 2023

How to Create a Html Files in Node.js?

Here's a basic Node.js script that generates single HTML file:

Source Code

import fs from 'fs'
const fileName = `example.html`
const htmlContent = `<!DOCTYPE html>
    <html>
    <head>
        <title>My HTML File</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>`
fs.writeFileSync("./pages/" + fileName, htmlContent);

Ouput:

pages/example.html

<!DOCTYPE html>
    <html>
    <head>
        <title>My HTML File</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>

If you want to generate multiple HTML files in a Node.js script, you can use a loop to create. Here's an example of how you can modify the script to generate multiple Markdown files:

Source Code

import fs from 'fs'
let noOfpages = [1, 2, 3, 4, 5]
for (let i = 0; i < noOfpages.length; i++) {
  const num = noOfpages[i];
  const fileName = `page-${num}.html`
  const htmlContent = `<!DOCTYPE html>
    <html>
    <head>
        <title>My HTML File</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>
`
  try {
    fs.writeFileSync("./pages/" + fileName, htmlContent);
    console.log('HTML file created successfully.');
  } catch (error) {
    console.error('Error creating HTML file:', error);
  }
}

In this example, we're using the built-in fs module in Node.js to create a HTML files.

Next, In this example, Each file has a name that includes a page number, such as "page-1.html," "page-2.html," and so on. these files are stored in a folder called "pages" . you can change the file name and folder name as needed.

You can also update HTML content.

Finally, we use the fs.writeFile() method to write the HTML content to the file.

To run this script, save it to a file with a .js extension (e.g., generateHTML.js), and execute it using Node.js:

node generateHTML.js

Ouput:

output-screenshot

Happy Coding! ❤️