Вставьте путь к файлу в большое количество файлов - PullRequest
0 голосов
/ 07 октября 2019

Мне нужно вставить отдельные пути к файлам и имена файлов в огромное количество файлов HTML. Путь следует вводить сразу после тега </title>.

Какой самый быстрый способ сделать это?

1 Ответ

1 голос
/ 08 октября 2019

Решение 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');
    });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...