artemean
artemean

Reputation: 855

How to parse functions bodies from a string using javascript?

I'm looking for a way to get a function declaration body by name from a string of js code. I'm in Nodejs environment. Let's say I have some spaghetti.js file. I can read it into a string

const allJs = fs.readFileSync('spaghetti.js');

Now I need a function that receives that string and function name and returns a string with everything between { }.

Something like this

allJs = 'let a=1; const b=[2, 3]; function cook(items){return items}; cook(b)';
parseFunction(allJs, 'cook');//'return items'

The complexity of input js is not limited.

I tried to find an npm module for that, but no luck.

Upvotes: 0

Views: 4203

Answers (2)

Brian Peacock
Brian Peacock

Reputation: 1849

A String can be evaluated locally with the native eval() method. But remember, eval is a form of evil!

If the parseFunction() above is relying on something like this then the global Function constructor is being used and the 'new' function is bound to the return value of that operation (and thus that return value itself needs to be called).

A simple way to achieve this might be to do something like this...

var funcString = 'var a = 1, b = 3;';
funcString += 'function summit(){return a + b;}';
funcString += 'return summit();';

function makeNewFunc(str) {
    return new Function(str);
}

var newFunc = makeNewFunc( funcString );

console.log('newFunc:',newFunc);
//-> newFunc: function anonymous()

console.log('newFunc():',newFunc());
//-> newFunc(): 4

This demonstrates how functions can be created and invoked from String snippets. (EDIT: Turning something like that into a Node module is a simple matter);

Hope that helped. :)

Upvotes: 0

dsuckau
dsuckau

Reputation: 592

You should have a look at an AST parser for Javascript:

http://esprima.org/

https://github.com/ternjs/acorn

That should be more safe than using RegExp or something.

Upvotes: 2

Related Questions