8

If I construct a function or list of commands that are stored in a string variable, is there a way I can execute them in node and retain what is returned in another variable? i.e.

var result = executeMyCoolStringCommands(myStringVariableWithCommands);
1
  • What is "executeMyCoolStringCommands" function and "myStringVariableWithCommands" variable? Show us some code! Commented Feb 19, 2016 at 14:58

3 Answers 3

17

option -e will let you run arbitary text as node.js source code:

node -e "console.log(JSON.stringify({}))"

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

Comments

7

Node has well-suited VM module, which allows you to run code in a dedicated context. See https://nodejs.org/api/vm.html

E.g.


const vm = require('vm');

const x = 1;

const context = { x: 2 };
vm.createContext(context); // Contextify the object.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the context.
// Initially, x has the value 2 because that is the value of context.x.
vm.runInContext(code, context);

console.log(context.x); // 42
console.log(context.y); // 17

console.log(x); // 1; y is not defined.

Comments

5

Sure, we all know evils of using eval, however the npm module eval avoids its use yet executes a string

var _eval = require('eval')
var res = _eval('var x = 123; exports.x = x')

console.log("here is res ", res);

which outputs :

here is res  { x: 123 }

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.