从node.js中的String执行函数

Execute function from String in node.js

本文关键字:执行 函数 String 中的 node js      更新时间:2023-09-26

有没有办法执行作为请求参数传递的String中的函数并在node.js中返回结果?想象一个包含String:的请求

"db.users.find()"

作为参数

如果我知道我想执行这个声明,我会这样做:

db.collection('users', function(err, collection) {
    collection.find().toArray(function(err, items) {
        res.send(items);
    });
});

我想要的是一个类似解析器的东西,它可以执行给定的语句并返回结果。

我试过这样:

exports.execStatement = function(req, res) {
//var statemnet = req.params.statement;
  var statement = "collection.find().toArray(function(err, items) {
        res.send(items);});";
  db.collection('users', function(err, collection) {        
    eval(statement)
   });
};

这个代码给我错误:

var statement = "collection.find().toArray(function(err, prdel) { ...
SyntaxError: Unexpected token ILLEGAL

怎么了?为什么我不能执行存储在字符串中的代码?完成这项工作后,我想弄清楚如何执行在请求中作为参数传递的代码。

这种方法可能吗?

第二个例子展示了如何将函数添加到数据库中。

http://mongodb.github.com/node-mongodb-native/api-generated/db.html#eval

但是不要。主要有三个原因

  1. 在2.2及更早版本中,SpiderMonkey是单线程的,这意味着"存储过程"的性能非常糟糕
  2. eval在操作期间需要写锁(除非您专门设置了nolock,然后最好不要写,否则会失败)。这将停止数据库上的所有写入操作,直到函数完成执行
  3. 注射攻击,但上面已经介绍过了