简体   繁体   English

Node.js从数据库加载脚本

[英]Node.js load script from database

I would like to add a «dynamic» part of my node backend, so that I can easily add/edit simple JS code snippets quickly. 我想在节点后端添加一个“动态”部分,以便可以轻松快速地添加/编辑简单的JS代码片段。 Ideally the JavaScript code for these snippets would be stored in the database, and loaded («required») directly from the db. 理想情况下,这些代码段的JavaScript代码将存储在数据库中,并直接从数据库加载(“必需”)。

If the code in the db changes, these change would take effect immediately - so the script should be loaded on every request. 如果数据库中的代码更改,则这些更改将立即生效-因此应在每个请求上加载脚本。

Is there a way to achieve this using Node.js? 有没有一种方法可以使用Node.js来实现?

You store the code as text entries in the database and retrieve it using database calls. 您可以将代码作为文本条目存储在数据库中,并使用数据库调用来检索它。 Doing that reactively is a question of its own and will depend on which database you are using (for instance, reacting to the oplog in Mongo). 被动地执行该操作本身是一个问题,并且将取决于您使用的是哪个数据库(例如,对Mongo中的oplog进行响应)。

After retrieving the text you will need to execute the code somehow. 检索文本后,您将需要以某种方式执行代码。 You can do this using eval in JavaScript, but you need to trust the code! 您可以在JavaScript中使用eval来执行此操作,但是您需要信任代码! You simply have to call eval(codeRetrievedFromDb); 您只需要调用eval(codeRetrievedFromDb); in javascript 在JavaScript中

Example : 范例:

var str_fun = "function custom_fun(arg) { return 'hello'; }";

eval(str_fun);

function usefun(x)
{
  var res = custom_fun(x);
  //print hello
  console.log(res);
}

For the second part of your question, I suggest to create a polling function accessing the database every X seconds. 对于问题的第二部分,建议创建一个每X秒访问数据库的轮询功能。

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

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