Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 809
Peter Savnik Avatar asked Oct 04 '17 09:10

Peter Savnik


People also ask

How do I call a node js function from a string?

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.

How do I run a function in node JS?

A function can be executed by calling the execute() method in which the function ID and configuration (of type JSON) are passed as parameters.

How do I run a JavaScript string?

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

How do I turn a string into a function?

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.


1 Answers

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

like image 53
Peter Savnik Avatar answered Oct 23 '22 01:10

Peter Savnik