[英]fs.readFile and variable passing in node
I have two variables like this in my node project我的节点项目中有两个这样的变量
header ="Hello Header";
result = `<html>
</head>
<body>
<div class='modal'>
<div class='header'>
${header}
</div>
</div>
</body>
</html>`;
I want to load this html part from an html file and pass the header value on to it.我想从 html 文件中加载这个 html 部件并将header值传递给它。 How we can achieve it?
我们怎样才能实现它?
I know we can use fs.readFile我知道我们可以使用 fs.readFile
fs.readFile("index.html", 'utf8', function (err, data) {
result = data;
});
But how can I pass the header variable into this?但是我怎样才能将header变量传递给这个变量呢?
The easiest and fastest solution would be to:最简单和最快的解决方案是:
make the replaceable header part in the HTML discoverable with a pattern like {{ header }}使用 {{ header }}
read the file as you would normally像往常一样读取文件
fs.readFile("index.html", 'utf8', function (err, data) { // make something here }); fs.readFile("index.html", 'utf8', function (err, data) { // 在这里做点什么 });
OR或者
you could use promises for better readability and compact code你可以使用 Promise 来获得更好的可读性和紧凑的代码
import {promises} from "fs"
(async () => {
const html = await promises.readFile(file, "utf8");
})()
then when you have the HTML in a variable just do:然后,当您在变量中有 HTML 时,只需执行以下操作:
data.replace("{{ header }}", header) data.replace("{{ header }}", 标头)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.