获取用户的输入并将其用作函数 [英] Get user's input and use it as a Function

查看:25
本文介绍了获取用户的输入并将其用作函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个测试用例可视化工具,用户可以在其中运行他的代码并检查它是否正确.我正在使用 Node Js,并且正在从文本区域获取用户代码.假设这是我从用户那里得到的:

I am working on a test case visualizer where the user can run his code and check if it is correct. I'm using Node Js and I'm getting user's code from a text-area. Assuming that this is what I'm getting from the user:

function add(x, y) {
    return x + y;
}

这就是我在后端所做的:

And this is what I'm doing at the backend:

app.post("/main", function(req, res) {
    console.log("hello");
    var x = 1;
    var y = 2;
    req.body.code //missing
})

如何将此输入用作函数并运行它以获取值?

How can I use this input as a function and run it to get the values?

推荐答案

我最终做的是我使用了 vm2 沙箱

What I ended up doing is that I used vm2 sandbox

vm2 是一个沙箱,它可以使用列入白名单的 Node 的内置模块运行不受信任的代码.它运行良好,您可以限制对某些方法的访问.

vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules. It works well, and you can limit access to certain methods.

首先需要它:

const { VM } = require('vm2');

然后,指定超时时间和沙箱:

then, specify the timeout, and the sandbox:

const vm = new VM({
    console: 'inherit',
    timeout: 1000,
    sandbox: { global_variable },
    require: {
        external: true,
    },
});

global_variable 只不过是一个var";我用来导出输出.

global_variable is nothing but a "var" that I used to export the output.

现在让我们在名为func"的字符串中使用以下函数:

Now let's use the following function in a string named "func":

function Main(x,y){
return x+y};

将其连接:

global_variable.exports=Main(5,5);

现在通过以下方式运行代码:

Now run the code via:

vm.run("func")

要打印答案,只需:

global_variable.exports;

只有当您有需要运行的 javascript 代码时,此解决方案才有效.我仍在寻找在 node js 中运行多种语言的其他解决方案.如果您有任何建议,请告诉我.

This solution works only if you have a javascript code that you need to run. I am still looking for other solutions that run for multiple languages in node js. If you have any suggestions please do let me know.

这篇关于获取用户的输入并将其用作函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆