Peter Savnik
Peter Savnik

Reputation: 813

Execute JavaScript functions from a string in nodejs

I have a data stream from a few sensors and I want my users to be able to create simple functions for processing this incoming data data. The users type in the function through a text field on a webpage and then the function is saved into a database. Whenever there is incoming data a nodejs service is receiving the data and process the data by the user defined function before saving the data it to a database.

How can I execute the user defined functions from the database?

For those who know TTN and their payload functions, this is basically what i want to do for my application. enter image description here

Upvotes: 9

Views: 7538

Answers (2)

Greg Frohring
Greg Frohring

Reputation: 39

Also, the built-in eval function,

like:

primes = [ 2, 3, 5, 7, 11 ]
subset = eval('primes.filter(each => each > 5)')
console.log(subset)

##outputs [ 7, 11 ]

Upvotes: 2

Peter Savnik
Peter Savnik

Reputation: 813

The solution was to use the VM api for nodejs. Playing a little around with this script helped a lot.

const util = require('util');
const vm = require('vm');

const sandbox = {
  animal: 'cat',
  count: 2
};

const script = new vm.Script('count += 1; name = "kitty";');

const context = new vm.createContext(sandbox);
for (let i = 0; i < 10; ++i) {
  script.runInContext(context);
}

console.log(util.inspect(sandbox));

// { animal: 'cat', count: 12, name: 'kitty' }

Thanks to @helb for the solution

Upvotes: 14

Related Questions