1

Is there any module to parse javascript using node.js . I mean we are able to add and remove html content dynamically using cheerio nodejs module.

Similarly, we want to add, remove and manipulate a javascript method/variable. Is there any module to do that. I searched but unable to get one.

Thanks in Advance !!!

1
  • 1
    Do you just want eval()? Commented Dec 11, 2014 at 6:41

1 Answer 1

3

I would recommend the recast module. Install it via npm install --save recast. Below is a sample program that will read in the source of a module named user.js in the current directory. It will parse the source into an AST then from the AST re-generate the original source. Modify the AST with help from estraverse before you call recast.print(ast).code.

The source (does not incorporate estraverse -- exercise for the reader):

'use strict';

var recast = require('recast');
var path = require('path');
var fs = require('fs');

var file = path.resolve(__dirname, 'user.js');
var code = fs.readFileSync(file).toString();
var ast = recast.parse(code);

var output = recast.print(ast).code;

console.log(output);
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.