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.
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method.
A function can be executed by calling the execute() method in which the function ID and configuration (of type JSON) are passed as parameters.
Use the setTimeout Function We can also pass in the JavaScript code string into the setTimeout function to run the code string. To do this, we write: const code = "alert('Hello World'); let x = 100"; setTimeout(code, 1);
To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With