作为一名程序员如何使用js将一个文件中包含另一个文件中的内容提取出来并写入filetxt文件中给出数据和完整代码
假设我们有两个文件:index.html和included.html,其中included.html包含一些内容需要提取出来。
index.html:
<html>
<head>
<title>Example</title>
<script src="main.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<div id="content"></div>
</body>
</html>
included.html:
<p>This is some included content.</p>
我们可以使用js将included.html中的内容提取出来,并写入file.txt文件中,代码如下:
main.js:
const fs = require('fs');
fs.readFile('included.html', 'utf8', (err, data) => {
if (err) throw err;
const content = data.match(/<p>(.*)<\/p>/)[1]; // 提取<p>标签中的内容
fs.writeFile('file.txt', content, err => {
if (err) throw err;
console.log('Content saved to file!');
});
});
运行上述代码后,会在当前目录下生成一个名为file.txt的文件,其中包含included.html中的内容:
file.txt:
This is some included content.
原文地址: https://www.cveoy.top/t/topic/bsFB 著作权归作者所有。请勿转载和采集!