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.
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!');
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With