我正在编写一个使用大多数填充的HTML模板的应用程序,并使用nodemailer发送电子邮件。我需要根据网络爬虫的发生情况,在特定位置写入到静态html文件中。
该节点具有一个id属性,我将其称为“ root”或“ insert_root”。
... MORE HTML ...
<tbody>
<tr>
<td class="pc-fb-font" style="padding: 20px 20px; text-align: center; font-...
<div id="insert_root" style="margin-left: 20px">
**Insert Here**
</div>
</td>
</tr>
</tbody>
... THE REST OF THE HTML ...
最简单,最可靠的方法是什么?我要插入的html内容如下所示:
<p style="margin-bottom: 10px; margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 600; line-height: 1.42; letter-spacing: -0.4px; color: #151515;">Coons, Christopher A:</p>
<ul style="margin-left: 20px; margin-top: 0px; padding: 0px; ">
<li style="margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 12px; font-weight: 500; line-height: 1.42; letter-spacing: -0.4px; color: #151515;"><a href=https://efdsearch.senate.gov/search/view/ptr/f06ca66b-6f1d-461e-990d-01e6bb206b51/>Periodic Transaction Report for 06/24/2019</a></li>
</ul>
<p style="margin-bottom: 10px; margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 600; line-height: 1.42; letter-spacing: -0.4px; color: #151515;">Roberts, Pat:</p>
<ul style="margin-left: 20px; margin-top: 0px; padding: 0px; ">
<li style="margin-left: 20px; font-family: Helvetica, Arial, sans-serif; font-size: 12px; font-weight: 500; line-height: 1.42; letter-spacing: -0.4px; color: #151515;"><a href=https://efdsearch.senate.gov/search/view/annual/ea3ce82e-f1e0-4f16-8498-79d02398f06c/>Annual Report for CY 2018</a></li>
</ul>
我认为我可以做一些事情,使用fs.readFile读取文件并将其写入,但是我想知道是否有一个更简单的解决方案涉及Cheerio或另一个HTML解析器以获取确切的根节点,并通过某种方式从中插入那里...有想法吗?
答案 0 :(得分:0)
正如劳伦斯指出的那样,我应该使用模板引擎。
我将<%= target%>和<%= targetTitle%>放在html文件中以接受文本。代码如下(在异步函数中):
const readFile = (fileName) => util.promisify(fs.readFile)(fileName, 'utf8');
const writeFile = (fileName, content) => util.promisify(fs.writeFile)(fileName, content, 'utf8');
let dynamicTtile = "titleIwanttoinsert";
let dynamicPost = "postIwantToInsert"
let html = await readFile(path.resolve(__dirname, "./emailContent/blankHtml/index.html"));
let tmpl = _.template(html);
let newHtml = tmpl({ target: dynamicHtml, targetTitle: dynamicTitle });
await writeFile(path.resolve(__dirname, 'emailContent', 'emails', 'sent', 'index.html'), newHtml);