是否可以定义一个评估动态 nodejs 代码的 NodeJs 函数?
这里是上下文:
用户创建应返回 true/false 的自定义 javascript 函数。
我需要“评估”在 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”未定义,因此 eval
未正确评估。
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
最佳答案
eval 在 Lambda 中运行良好。删除 'use strict' 它将正常工作,输出 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);
};
关于node.js - AWS Lambda 执行动态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47012959/