我需要将单个文件路径和文件名插入到大量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');
});
});