代码之家  ›  专栏  ›  技术社区  ›  Catalin

AWS Lambda执行动态代码

  •  3
  • Catalin  · 技术社区  · 7 年前

    以下是上下文:

    用户创建自定义javascript函数,该函数应返回true/false。

    我需要在运行在NodeJs上的AWS Lambda容器中“评估”用户代码。

    有可能吗?

    我应该使用类似javascript的东西吗 eval 作用

    编辑

    'use strict';
    
    exports.handler = (event, context, callback) => {
        var body = "function test() { return 10; };";
        console.log("body", body);
    
        eval(body);
    
        var result = test();
    
        callback(null, result);
    };
    

    我得到一个错误,说“test”没有定义,因此 评估 未正确评估。

    START RequestId: 6e9abd93-bd69-11e7-a43f-c75328d778e1 Version: $LATEST
    2017-10-30T11:56:58.569Z    6e9abd93-bd69-11e7-a43f-c75328d778e1    body function test() { return 10; };
    2017-10-30T11:56:58.581Z    6e9abd93-bd69-11e7-a43f-c75328d778e1    ReferenceError: test is not defined
        at exports.handler (/var/task/index.js:11:18)
    END RequestId: 6e9abd93-bd69-11e7-a43f-c75328d778e1
    REPORT RequestId: 6e9abd93-bd69-11e7-a43f-c75328d778e1  Duration: 32.78 ms  Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 19 MB  
    RequestId: 6e9abd93-bd69-11e7-a43f-c75328d778e1 Process exited before completing request
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   user7401700 user7401700    7 年前

    eval在Lambda中运行良好。移除 它可以正常工作,输出10。

    严格模式不允许创建全局变量,这就是为什么会出现错误。

    第二种选择是明确地将函数添加到全局上下文中:

    'use strict';
    
    exports.handler = (event, context, callback) => {
        var body = "global.test = function() { return 10; };";
        console.log("body", body);
    
        eval(body);
    
        var result = test();
    
        callback(null, result);
    };
    
        2
  •  0
  •   Vijayanath Viswanathan    7 年前

    节点只是在服务器端执行javascript的运行时。您可以在节点(Lambda)内编写任何有效的Javascript代码。

    正如我在代码“eval”中看到的,您可以尝试安装“npm install eval”包吗- https://www.npmjs.com/package/eval