2

I want to write a program that will add a line to JS within an existing HTML file. I thought I would use node.js as it's the same language.

I have looked at a number of projects, esprima, acorn, rocambole, falafel, escodegen etc. but I can't seem to find any documentation on how to add a node into the AST in order to create this new line. I wonder if a parsing tool is the best thing to use for this - perhaps I would be better using striing manipulation / regex? I also want to modify some lines as well as adding new ones. The code below is the non-working code I currently have to add a line into javascript.

var newNode = JSON.parse(transparent);

// get html string here
fs.readFile(path.normalize('C:\myDoc'), function (err, html) {
    if (err) {
        throw err;
    }

    handler = new htmlparser.DomHandler(function (err, dom) {
        if (err) {
            sys.debug("Error: " + err);
        } else {
            //      console.log(dom);
            var scripts = select(dom, 'body script');

            scripts.forEach(function (script) {
                if (typeof script.attribs.src === 'undefined') {
                    var ast = rocambole.parse(script.children[0].data);
                    rocambole.recursive(ast, function (rootNode) {

                        if (rootNode.type == "VariableDeclaration") {
                            rocambole.recursive(rootNode, function (node) {
                                if (node.type === "Identifier" && node.name === "params") {
                                    // I need to insert a new node after rootNode here
                                    console.log(escodegen.generate(rootNode.root));
                                }
                            });
                        }
                    });
                }
            })
        }
    })
    new htmlparser.Parser(handler).parseComplete(html);
});
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Stev_k
  • 2,118
  • 3
  • 22
  • 36
  • to answer the part about using simpler string.regexp methods: it depends on where the newline needs to go, and what you would be replacing. also, as white-space is sucked-up by most parsers, i'm not sure an AST will be of much help. you might look into how beautify scripts work. – dandavis Jun 13 '14 at 00:34
  • Can't speak for esprima, but can tell you regexes are bad news for making source code changes. See a virtually identical discussion for Java: http://stackoverflow.com/questions/24185601/edit-java-source-files-programatically/24188984#24188984 – Ira Baxter Jun 13 '14 at 01:32

0 Answers0