Edit elements in the jsdom window and save the window as a new HTML file?

一个人想着一个人 提交于 2020-05-10 00:47:00

问题


I want to load an HTML file (using fs.read), load the DOM using jsdom, and then change the text of the nodes of the body (via jquery). Then I want to save the edited DOM window as an HTML file. Is there a way to do this? The code I am using is the following:

fs.readFile(file, 'utf8', function(error, data) {
    jsdom.env(data, [], function (errors, window) {
        var $ = require('jquery')(window);
        $(document.body.getElementsByTagName("*")).each(function () {
            var content = $(this).text();
            var word = "\\b"+wordSuggestions.word+"\\b";
            var re = new RegExp(word, "g");
            content = content.replace(re, wordSuggestions.suggestion);
            $(this).text(content);
        });

        fs.writeFile(file, data, function (error){ // saving the new HTML file? What should I put instead of data? Window?
        });
    });
});

回答1:


Here's an example of how to do it. I've based it on your code but simplified it a bit so that I'd have code that executes and illustrates how to do it. The following code reads foo.html and adds the text modified! to all p element and then writes it out to out.html. The main thing you were missing is window.document.documentElement.outerHTML.

var jsdom = require("jsdom");
var fs = require("fs");

fs.readFile('foo.html', 'utf8', function(error, data) {
    jsdom.env(data, [], function (errors, window) {
        var $ = require('jquery')(window);
        $("p").each(function () {
            var content = $(this).text();
            $(this).text(content + " modified!");
        });

        fs.writeFile('out.html', window.document.documentElement.outerHTML,
                     function (error){
            if (error) throw error;
        });
    });
});



回答2:


There's no jsdom.env() anymore, and I think this example is easier to understand:

const fs = require('fs');
const jsdom = require('jsdom');
const jquery = require('jquery');

fs.readFile('1.html', 'utf8', (err, data) => {
    const dom = new jsdom.JSDOM(data);
    const $ = jquery(dom.window);
    $('body').html('');
    fs.writeFile('2.html', dom.serialize(), err => {
        console.log('done');
    });
});


来源:https://stackoverflow.com/questions/30120351/edit-elements-in-the-jsdom-window-and-save-the-window-as-a-new-html-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!