[英]Passing additional parameters to the callback of fs.readFile in Node js
[英]fs.readFile and variable passing in node
我的節點項目中有兩個這樣的變量
header ="Hello Header";
result = `<html>
</head>
<body>
<div class='modal'>
<div class='header'>
${header}
</div>
</div>
</body>
</html>`;
我想從 html 文件中加載這個 html 部件並將header值傳遞給它。 我們怎樣才能實現它?
我知道我們可以使用 fs.readFile
fs.readFile("index.html", 'utf8', function (err, data) {
result = data;
});
但是我怎樣才能將header變量傳遞給這個變量呢?
最簡單和最快的解決方案是:
使用 {{ header }}
像往常一樣讀取文件
fs.readFile("index.html", 'utf8', function (err, data) { // 在這里做點什么 });
或者
你可以使用 Promise 來獲得更好的可讀性和緊湊的代碼
import {promises} from "fs"
(async () => {
const html = await promises.readFile(file, "utf8");
})()
然后,當您在變量中有 HTML 時,只需執行以下操作:
data.replace("{{ header }}", 標頭)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.