I am using escodegen
to add an ending code on my statement as below. In the leave method, I append a .toArray()
call on the end of the statement.
const esprima = require('esprima');
const estraverse = require('estraverse');
const escodegen = require('escodegen');
const ast = esprima.parse('db.find()');
let finished = false;
estraverse.traverse(ast, {
leave: (node, parent) => {
if (node.type === esprima.Syntax.ExpressionStatement && !finished) {
finished = true;
let statement = escodegen.generate(node);
statement = `${statement.substring(0, statement.lastIndexOf(';'))}.toArray()`;
const findAst = esprima.parse(statement);
node.arguments = findAst.body[0].expression.arguments;
node.callee = findAst.body[0].expression.callee;
node.type = findAst.body[0].expression.type;
}
},
});
const generated = escodegen.generate(ast);
console.log('generated code:', generated);
The output from above code is: generated code: (db.find().toArray())
.
I don't understand why it wraps a parenthesis on my source code. Is there anything wrong in my source code?