简体   繁体   English

如何从文本文件读取数据,更改数据并将其附加到html?

[英]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

<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 我有来自服务器abc的数据。我希望节点从.txt文件中读取此数据,用数据替换模板文字,然后将其附加到另一个.html文件中。

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? 我要去哪里错了?

It is better to use templating engine such as Mustache . 最好使用诸如Mustache之类的模板引擎。 For example: 例如:

Your txt file: 您的txt文件:

<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!');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM