BenMQ
BenMQ

Reputation: 876

How to get NodeJS to evaluate multiple traditional JS files

We are using nodejs as an js engine to evaluate some student scripts on the server side so we can test their correctness.

Is there a way we can 'require' or 'import' multiple traditional .js files? We need to include submissions from multiple users. Or I'd have to concatenate the files?

Upvotes: 1

Views: 998

Answers (1)

freakish
freakish

Reputation: 56587

Yes, Node.JS (like most high level languages) supports dynamic import. If you have a list of files, for example

var files = ["student1.js", "student2.js", "student3.js", ...];

then you can simply do

files.forEach(function(f) {
    try {
        require(f);
    } catch(e) {
        console.log("Error in file: "+f);
    }
});

this will automatically import and evaluate these files. Note that it might throw an exception (because of errors in files),so that's why it is wrapped with try{}catch{}.

However if you keep scripts in database and in Node.JS you only have them as strings then you could use eval:

var scripts = ["var x = 1;", "console.log('test');", ...];
scripts.forEach(function(s) {
    try {
        eval(s);
    } catch(e) {
        console.log("Error in script:\n"+s);
    }
});

Of course "traditional" (I assume that by that you mean browser-side JavaScript) scripts may not be compatibile with Node.JS (for example there is no window in Node.JS).

WARNING: Note that both methods are unsafe (users can upload malicious scripts), so perhaps the best idea would be to spawn a separate Node.JS process (in restricted environment) for each one of them. You could write a script for that as well, it's just a bit more complicated.

Upvotes: 3

Related Questions