【问题标题】:Insert file path into a large number of files将文件路径插入大量文件
【发布时间】:2019-10-07 20:44:06
【问题描述】:

我需要将单独的文件路径和文件名插入到大量 HTML 文件中。路径应在</title> 标记之后输入。

最快的方法是什么?

【问题讨论】:

    标签: html text replace path


    【解决方案1】:

    解决方案 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');
        });
    });
    

    【讨论】:

    • 我不想将这些字符串插入 DOM。我需要将它们永久保存在 HTML 文件中。
    • @KnocksX 两种解决方案都只这样做(第二个答案只是以 DOM 方式修改然后存储)[old.html -> new.html]
    • @KnocksX 输出将类似于 之后
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2011-05-17
    • 2012-10-03
    • 2020-11-30
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多