AWS Lambda execute dynamic code

╄→尐↘猪︶ㄣ 提交于 2020-12-05 12:41:27

问题


Is it possible to define a NodeJs function which evaluates dynamic nodejs code?

Here is the context:

The user creates custom javascript function which should return true / false.

I need to "evaluate" the user code in a AWS Lambda container, which runs on NodeJs.

Is it possible?

Should i use something similar to javascript eval function?

EDIT

Here is what i tried

'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);
};

And i get an error saying "test" is not defined, therefore eval was not evaluated properly.

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

回答1:


eval works fine in Lambda. Remove the 'use strict' and it will work fine, outputting 10.

strict mode doesn't allow creating global variables, that's why you're getting the error.

A second option is to explicity add the function to the global context:

'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:


Node is just a runtime to execute javascript on the server side.You can write any valid Javascript code inside Node (Lambda).

As I could see in code 'eval' is not executing can you please try by installing the package 'npm install eval' - https://www.npmjs.com/package/eval



来源:https://stackoverflow.com/questions/47012959/aws-lambda-execute-dynamic-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!