Node js build html

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Generate HTML with node.js

License

Hargne/html-creator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

const htmlCreator = require("html-creator"); const html = new htmlCreator([  type: "head", content: [  type: "title", content: "Generated HTML", >,  type: "style", content: ` #cool-text  color: red; > `, >, ], >,  type: "body", content: [  type: "div", content: [  type: "div", content: "This is a cool text 😎", attributes:  id: "cool-text" >, >,  type: "a", content: "Click here", attributes:  href: "/path-to-infinity", target: "_blank" >, >, ], >, ], >, ]); const result = html.renderHTML();

The above code will result with the following HTML output:

> html> head> title>Generated HTMLtitle> style> #cool-text < color: red; > style> head> body> div> div id pl-s">cool-text">This is a cool text 😎div> a href pl-s">/path-to-infinity" target pl-s">_blank">Click herea> div> body> html>

Visit the wiki for more examples of usage, method reference and further reading.

Do you believe that something is missing from this plugin or perhaps is not working as intended? Awesome-pants! Help is always appreciated. Just be sure to read through the Contributing Handbook (and remember to have a jolly good time).

About

Generate HTML with node.js

Источник

How to generate an HTML table and a PDF with Node & Google Puppeteer

Adeel Imran

Adeel Imran

How to generate an HTML table and a PDF with Node & Google Puppeteer

image-244

Understanding NodeJS internally can be a little bit daunting (I know it was for me once). Node is a very powerful language and it can do a lot of things.

Today I wanted to uncover the power of Node’s built-in utility tool called fs (file system)

The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.

Which is just a fancy way of saying that file system is a way in Node to interact with files for both read and write operations.

Now file system is a humongous utility in NodeJS that has a lot of fancy features. In this article, however I will only discuss 3:

  • Getting file information: fs.statSync
  • Deleting a file: fs.unlinkSync
  • Writing data to a file: fs.writeFileSync

Another thing we will cover in this article is Google Puppeteer which is this really cool, slick tool created by some awesome folks at Google.

So what is puppeteer? Well as per the docs, they say:

Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromium.

So it’s basically a tool that lets you do all the cool browser related things on server. Like getting a website’s screenshots, crawling websites, and generating pre-render content for single page applications. You can even do form submissions via your NodeJS server.

Again puppeteer is a huge tool, so we will cover just a small but a very cool feature of puppeteer. We’ll look at how to generate a nice PDF file based on our generated HTML table file. In the process we’ll learn about puppeteer.launch() and understand a bit about page() & pdf().

So to again give a brief overview, things we will cover:

  • Generating stub data (for invoices) using an online tool.
  • Creating an HTML table with a little bit of styling with generated data in it, using an automated node script.
  • Learning about checking if a file exists or not using fs.statSync
  • Learning about deleting a file by using fs.unlinkSync
  • Learning about writing a file using fs.writeFileSync
  • Creating a PDF file of that HTML file generated using Google puppeteer
  • Making them into npm scripts, to be used later ? ?

Also before we begin here is the entire source code of the tutorial, for everyone to follow along. You don’t have to write anything, but you should write code along with this tutorial. That will prove more useful & you’ll understand more. SOURCE CODE OF TUTORIAL

Before we begin, please ensure that you have at least the following installed on your machine

You don’t need to, but you can also watch an introductory video (my first ever made) that talks about the basics in reading, writing, and deleting a file in NodeJS. This will help you understand this tutorial. (Please do give me feedback). ?

lnYaAbNKig8Zhhuqh1QQDnMGFcQ1KNcHAA2I

Also you can add an npm script in your package.json like this:

This way instead of writing npm run ./createTable.js , you can just type in npm run build:table .

Next up: generating a PDF from the generated HTML file.

Step 8:

First things first we need to install a fancy tool, so go in your terminal in your application folder and type in

Step 9:

In the same folder where you have files createTable.js , buildPaths.js & data.json , create a new file called createPdf.js and add content to it like below:

UOMwXytU2JyC8VlsgaM-wXF-9D9icvPpLlnC

And that is it, we are done.

You have learned the following:

  • How to check if a file exists / tet file information (in Node)
  • How to delete a file in Node
  • How to write to a file
  • How to use Google Puppeteer to generate a PDF file

Happy learning, I would love to hear your thoughts on this article. You can reach me on twitter as well.

Источник

HTML Templating in NodeJs

HTML templating is a technique that allows us to create a base HTML structure and use placeholders to dynamically generate content based on data retrieved from our JSON file or database. Let’s consider a hypothetical instance where our website consists of numerous product cards, each containing specific product details that are retrieved from the JSON file. Now, if we were to add or remove any products from our JSON file, how would we update the corresponding cards on the front-end dynamically? Considering our content-based data is stored in a JSON file, we can proceed with creating reusable templates from our existing HTML code. Step 1: Building the templates
As a developer, you’re probably familiar with the concept of serving dynamic web content. One way to achieve this is by using templates. We would create two HTML templates, one for the product overview page and one for the individual product cards. The first template template-card.html is used as a blueprint for the individual product cards, and the second template-overview.html is used as a blueprint for the overview page. These templates contain placeholders that will be replaced with actual content when the page is requested by a user. Ensure that your placeholder does not contain any symbols that are part of the HTML code. A commonly used syntax for placeholders is . Here is template-card.html our first template used as a blueprint to create as many cards as needed dynamically.

 
Organic!
per 📦
"> Detail 👉

As this card will serve as a template, the information contained within it should be replaced with placeholders as well. Once the placeholders have been added, the card will resemble the following:

 
🥦🥦

Apollo Broccoli

Organic!
3🥦 per 📦
5.50€
Detail 👉

The anchor tag contains an href link that includes a placeholder for an ID. This indicates that each card or product in our JSON file has a distinct ID. These IDs are unique and will be utilized in identifying each product during routing. Also, when we need to style elements based on their category, CSS classes and IDs can be substituted with placeholders as is done in the image examples. This approach can prove especially useful in such cases.

In this example, we have substituted our template card with a placeholder. It’s important to keep in mind that we will generate multiple cards dynamically using this single template card. Note: This is our second template card, template-overview.html Step 2: Filling the templates
Here comes the fun part, filling our templates by replacing our placeholders with actual content. When a user requests a URL, the code reads the relevant template file (either template-overview.html or template-card.html ) synchronously, fills it dynamically with content from a JSON file, and sends back the relevant content as a response to the user. This is achieved through the use of the replaceTemplate function, which replaces the placeholders in the template with actual content.

// SECOND STEP: const replaceTemplate = (temp, product) => < let output = temp.replace(//g, product.productName); output = output.replace(//g, product.image); output = output.replace(//g, product.price); output = output.replace(//g, product.id); // /g is a regex global flag return output; > // FIRST STEP: const tempOverview = fs.readFileSync(`$/templates/template-overview.html`, 'utf-8'); const tempCard = fs.readFileSync(`$/templates/template-card.html`, 'utf-8'); const data = fs.readFileSync(`$/dev-data/data.json`, 'utf-8'); const dataObj = JSON.parse(data); // THIRD STEP: const server = http.createServer((req, res) => < const pathName = req.url; //FOURTH STEP: //Here is the Overview if(pathName === '/' || pathName === '/overview') < res.writeHead(200, ); const cardsHtml = dataObj.map(el => replaceTemplate(tempCard, el)).join(''); const output = tempOverview.replace(' else if(pathName === '/api') < res.writeHead(200, ); res.end(data); // Not Found > else < res.writeHead(404, < 'Content-type': 'text/html', //standard header 'my-header': 'hello-world' >); res.end('

This page cannot be found.

'); > >); server.listen(8000, '127.0.0.1', () => < console.log('Listening to requests on port 8000'); >); res.writeHead(404, < 'Content-type': 'text/html', //standard header 'my-header': 'hello-world' >); res.end('

This page cannot be found.

'); > >); server.listen(8000, '127.0.0.1', () => < console.log('Listening to requests on port 8000'); >);
  • First, read the two HTML template files and the product data that is stored in a JSON file
  • Second, define a function that replaces placeholders in the templates with product-specific data. Here, our function is named replaceTemplate
  • Third, listen to incoming HTTP requests and check the pathname of the request URL
  • Fourth, If the pathname is / or /overview , generate HTML code for each product card by replacing placeholders in the tempCard template using the replaceTemplate function and the product data from the JSON file.
  • The resulting HTML for each card is then concatenated to create the cardsHtml string. The tempOverview template is then modified to include the cardsHtml string and the resulting HTML code is sent back as the response.
  • Also, if the pathname is /api it sends back the product data in JSON format as the response
  • Finally, if the pathname is anything else, sends back a 404 error message.

Wow, that code did look like a lot, but if we look closely and take it one step at a time, it’s not that complicated.

All it’s doing is replacing some special words with real information and sending it back to the website so people can see it!

Benefits of HTML templating
HTML templating offers several benefits that make it a popular choice among web developers:

  • By utilizing HTML templating, we separate content from the presentation allowing developers to generate reusable templates that can handle varying amounts of data from multiple sources, and maintain multiple copies of similar code.
  • HTML templates provide a standard structure for presenting data, improving user experience and easy navigation on the site.
  • The flexibility of templating makes it easier to modify the underlying data. This saves time and effort, as developers don’t need to change the HTML code manually.
  • Since HTML templates are reusable, they are easier to maintain and update. Changes to the underlying data can be made without modifying the template code, which reduces the likelihood of errors.
  • HTML templating can handle large amounts of data without compromising performance. This makes it an ideal choice for websites with a significant amount of dynamic content.

In summary, HTML templating is an efficient, consistent, flexible, and scalable technique that simplifies the development and maintenance of dynamic web content.

By separating content from presentation, HTML templating enables developers to create reusable templates that can handle varying amounts of data, without having to hard-code the content into each page.

Bonus Section:
There are several other templating engines available in Node.js, such as EJS, Pug (formerly known as Jade), Handlebars, and Mustache, among others.

To use a templating engine in Node.js, you’ll need to install it via npm and then require it in your code. These engines provide a way to generate HTML by inserting data into placeholders within the template.

You’ve reached the end of the article! 🎉 Hope you enjoyed this post and learned something new 💡.
Thanks for sticking around.

Источник

Читайте также:  Java виды garbage collectors
Оцените статью