Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
        });
    });
});
like image 494
Eva Avatar asked May 08 '15 09:05

Eva


2 Answers

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;
        });
    });
});
like image 164
Louis Avatar answered Sep 19 '22 20:09

Louis


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');
    });
});
like image 39
x-yuri Avatar answered Sep 16 '22 20:09

x-yuri