html - 将文件路径插入大量文件
问题描述
我需要将单个文件路径和文件名插入到大量 HTML 文件中。路径应该在</title>
标签之后输入。
最快的方法是什么?
解决方案
解决方案 1
const fs = require("fs");
const nodePath = require('path');
const path = 'C:\\Users\\Sudhakar_r_R\\Desktop\\test';
function change(path) {
const files = fs.readdirSync(path);
files.forEach((i) => {
let x = nodePath.join(path, i);
if (fs.statSync(x).isFile()) {
fs.readFile(x, 'utf-8', function (err, data) {
if (err) throw err;
let newStuff = data.replace('</title>', `</title><!-- fullpath: ${x} filename: ${nodePath.basename(x)} path: ${nodePath.dirname(x)} -->`);
fs.writeFile(x, newStuff, 'utf-8', function (err) {
if (err) throw err;
console.log(x,"done");
});
})
}
else {
change(x);
}
});
}
change(path);
解决方案2(使用' jsdom ')
const jsdom = require("jsdom");
const fs = require("fs");
const { JSDOM } = jsdom;
JSDOM.fromFile("./old.html", { runScripts: "dangerously" }).then(dom => {
let node = dom.window.document.getElementsByTagName('title')[0];
// you can create html elements or put it in string format
node.insertAdjacentHTML('afterend', '</title><script src="test.js"></script>');
fs.writeFile('new.html', dom.serialize(), 'utf-8', function (err) {
if (err) throw err;
console.log('Now, you can check the output');
});
});
推荐阅读
- java - 如何从android中的嵌套对象访问setter?
- python - 如何将多个(不同)模型对象显示给一个 tempate django
- android-studio - 如何启用 Android Studio 来检测丢失的 JSON?
- javascript - 如何在 react native 中使用 props 进入下一页?
- javascript - 减少和限制集合组合搜索的内存使用的算法
- python - 使用 except 块捕获整数输入范围之外的数值
- python - 我如何实现这个 Flask?
- python - 创建一个新键并分配嵌套字典中现有键的值
- python - Numpy:我如何进入“exp中遇到的溢出”?
- php - 如何使用 PHP 从数组中提取特定的 JSON 对象