Решение 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');
});
});