1

I wrote the application in node.js which collects data in the MongoDB database. I.e.:

  • name: John
  • pagename: mypage
  • links: [link1, link2, link3]

I need to create static HTML pages with pagename.mydomainname.com, put content from variables (name, link1, link2..) inside this HTML pages

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p>My name is - name</p>
    <p>My link 1 is - link1</p>
    <p>My link 2 is - link2</p>
    <p>My link 3 is - link3</p>
</body>
</html>

And store this HTML files on the server in the special folder. How to do it using Nodejs?

1 Answer 1

1

You want a templating library. One of the easiest to use and most popular templating libraries is called handlebars.

https://www.npmjs.com/package/handlebars

With handlebars you define a template, then throw JSON at the template and it spits out the response.

Here's an example given on the npm page:

var source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
         "{{kids.length}} kids:</p>" +
         "<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
var template = Handlebars.compile(source);

var data = { "name": "Alan", "hometown": "Somewhere, TX",
         "kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
var result = template(data);

Would render:

Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:

  • Jimmy is 12
  • Sally is 4

The handlebars documentation is good. http://handlebarsjs.com/

There are other templating libs but this is number one.

nunjucks is another good one. https://www.npmjs.com/package/nunjucks

And there are others, just search for handlebars alternatives if interested.

Using one of these templating libs, you would write the output data to file using fs.writeFile

If you want a simpler one that runs from the command line and has file generation built in, try envsub.

https://www.npmjs.com/package/envsub

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

2 Comments

Thanks. Read bit about it. And how to store html file on disk?
fs.writeFile - see edited answer and link to docs or fs.writeFileSync

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.