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);
});