Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and modify HTML from a local file with JavaScript

I can't think of an elegant solution. But, what would be the best way to process an HTML file, modify it and save it back using a script on the command line? I want to basically run this script, proving the HTML file as an argument, add a data-test=<randomID> into every <div> element, and save it back into the file. I was thinking I could write a JavaScript script to execute with node but am not sure how I would get the contents of the provided file, or what to store the content as. Thanks for any pointers.

like image 425
mart1n Avatar asked Sep 06 '13 08:09

mart1n


1 Answers

Solved with jsdom (thanks for the tip, user1600124):

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

if (process.argv.length < 3) {
  console.log('Usage: node ' + process.argv[1] + ' FILENAME');
  process.exit(1);
}

var file = process.argv[2];
fs.readFile(file, 'utf8', function(err, data) {
    if (err) throw err;

    jsdom.env(
        data,
        ["http://code.jquery.com/jquery.js"],
        function (errors, window) {
            var $ = window.jQuery;

            $("p, li").each(function(){
                $(this).attr("data-test", "test");
            });
            $(".jsdom").remove();
            console.log( window.document.doctype + window.document.innerHTML );
            var output = window.document.doctype + window.document.innerHTML;

            fs.writeFile(file, output, function(err) {
                if (err) throw err;
                console.log('It\'s saved!');
            });
     });
});
like image 154
mart1n Avatar answered Nov 02 '22 23:11

mart1n