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.
-
Do you mean using node.js to host a page that would act as the editor for you to edit other html files?user1600124– user16001242013-09-06 08:15:08 +00:00Commented Sep 6, 2013 at 8:15
-
1@user1600124, no, I just want a quick command line script that, given an HTML file, will modify it. This is all done locally, hosting the file is not a requirement.mart1n– mart1n2013-09-06 08:16:47 +00:00Commented Sep 6, 2013 at 8:16
-
so.. each <div.... ></div> => <div data-test="someid"...></div>?user1600124– user16001242013-09-06 08:17:36 +00:00Commented Sep 6, 2013 at 8:17
-
2That... is a bit difficult... Maybe check out jsdom.... But installing jsdom was a bit hassle for me... And I haven't got it to work yet..user1600124– user16001242013-09-06 08:56:53 +00:00Commented Sep 6, 2013 at 8:56
-
1@user1600124, thanks for the tip. That's what I was looking for. Check my answer for the solution ;-)mart1n– mart1n2013-09-06 09:27:59 +00:00Commented Sep 6, 2013 at 9:27
|
Show 3 more comments
1 Answer
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!');
});
});
});