9

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

1
  • 3
    VM API: nodejs.org/api/vm.html (or just eval, but it's always good to have a sandbox for executing user-supplied code) Commented Oct 4, 2017 at 12:22

2 Answers 2

14

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

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

Comments

1

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 ]

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.