Saikiran
Saikiran

Reputation: 776

How to read data from text file, change the data and append it to a html?

I have data in a text file that contains HTML with template literals like this

<html>
<head></head>
<body>
<p>`${abc}`</p>
</body>
</html>

I have data from the server abc.. I want node to read this data from the .txt file , replace template literals with the data and then append it to another .html file.. This is what I tried

var abc =  "Hi there"
var dat = fs.readFileSync('home.txt', 'utf8');
fs.writeFile('index.html', dat, (err) => {
     if (err) throw err;
        console.log('The file has been saved!');
    });

Where am i going wrong?

Upvotes: 0

Views: 373

Answers (1)

Tolsee
Tolsee

Reputation: 1705

It is better to use templating engine such as Mustache. For example:

Your txt file:

<html>
<head></head>
<body>
<p>{{abc}}</p>
</body>
</html>

And your code:

const Mustache  = require('mustache')

var abc =  "Hi there"
var dat = fs.readFileSync('home.txt', 'utf8');
var html = Mustache.render(dat, {abc: abc});
fs.writeFile('index.html', html, (err) => {
 if (err) throw err;
    console.log('The file has been saved!');
});

Upvotes: 1

Related Questions