最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Execute JavaScript functions from a string in nodejs - Stack Overflow

programmeradmin8浏览0评论

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.

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.

Share Improve this question edited Oct 4, 2017 at 12:14 Peter Savnik asked Oct 4, 2017 at 9:55 Peter SavnikPeter Savnik 8131 gold badge10 silver badges30 bronze badges 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) – helb Commented Oct 4, 2017 at 12:22
Add a comment  | 

2 Answers 2

Reset to default 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

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 ]
发布评论

评论列表(0)

  1. 暂无评论