6

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.

8
  • Do you mean using node.js to host a page that would act as the editor for you to edit other html files? Commented 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. Commented Sep 6, 2013 at 8:16
  • so.. each <div.... ></div> => <div data-test="someid"...></div>? Commented Sep 6, 2013 at 8:17
  • 2
    That... 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.. Commented 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 ;-) Commented Sep 6, 2013 at 9:27

1 Answer 1

10

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!');
            });
     });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.