简体   繁体   English

从 nodejs 中的字符串执行 JavaScript 函数

[英]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.每当有传入数据时,nodejs 服务都会接收数据并在将数据保存到数据库之前通过用户定义的函数处理数据。

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.对于那些了解 TTN 及其有效载荷功能的人来说,这基本上就是我想要为我的应用程序做的事情。 在此处输入图片说明

The solution was to use the VM api for nodejs.解决方案是将 VM api 用于 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感谢@helb 的解决方案

Also, the built-in eval function,此外,内置的 eval 函数,

like:像:

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

##outputs [ 7, 11 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM