Ken
Ken

Reputation: 215

Can I execute a string command in Node?

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);

Upvotes: 7

Views: 18038

Answers (3)

Do-do-new
Do-do-new

Reputation: 992

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.

Upvotes: 7

jiogai
jiogai

Reputation: 181

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

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

Upvotes: 16

Scott Stensland
Scott Stensland

Reputation: 28335

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 }

Upvotes: 5

Related Questions