Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I execute a string command in Node?

Tags:

node.js

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);
like image 775
Ken Avatar asked Dec 14 '22 08:12

Ken


2 Answers

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

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

like image 166
jiogai Avatar answered Dec 31 '22 22:12

jiogai


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 }
like image 24
Scott Stensland Avatar answered Dec 31 '22 22:12

Scott Stensland