0

is it possible to parse a node js file and run part of the code from inside of another node js file?

I have a node.js file that I am trying to parse from inside another node.js script. I don't control the contents of the file, but it is valid node.js and it always has a function inside of the code called: getParameterDefinitions

Here is a file I am trying to parse: https://github.com/jscad/OpenJSCAD.org/blob/master/examples/gear.jscad

Specifically I want the JSON array returned from getParameterDefinitions as a variable in my code.

Here is the code I have currently:

const fs = require('fs')
inputFile = 'gear.jscad'
let src = fs.readFileSync(inputFile, 'UTF8')
console.log(src)
params = Parse(src,'getParameterDefinitions') //how to write this line?

How can I have node parse the javascript and run the function to get me back the results into the params variable.

4
  • 1
    If you think the code is safe, then use eval. Commented Dec 21, 2017 at 22:25
  • even with eval, how do I call the getParameterDefinitions function? Commented Dec 21, 2017 at 22:30
  • 2
    function getValues(code) { eval(code); return getParameterDefinitions(); }. Then call it like: var params = getValues(src);. BUT only if you're sure src doesn't contain any harmful code. Commented Dec 21, 2017 at 22:36
  • Its not eval(code) its evil(code). ;) BTW, avoid eval at all costs especially in node. Commented Dec 22, 2017 at 8:54

1 Answer 1

1

Some people may suggest using eval. But there's a slightly cleaner way: the Function constructor - see here. Then do this:

const getGetParameterDefinitions = new Function(src + ";\nreturn getParameterDefinitions;");
const getParameterDefinitions = getGetParameterDefinitions();
const params = getParameterDefinitions();

or else this:

const getParameterDefinitions = new Function(src + ";\nreturn getParameterDefinitions();");
const params = getParameterDefinitions();

(Note: the argument to Function is slightly different in these two cases.)

This is still a bad idea though - don't do it unless you trust the people who wrote the code.

Also, I'm assuming that the function getParameterDefinitions is declared in the outermost scope of the src script.

Sign up to request clarification or add additional context in comments.

2 Comments

this code doesnt seem to work, it returns this: [Function: getParameterDefinitions]
Yes, that was the function you needed to call. I've now added that bit on the end of the answer.

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.