RaphaMex
RaphaMex

Reputation: 2839

How to manage a fully separate context with nodejs?

I am writing a javascript test framework based on nodejs. My server reads javacript files, instruments them, then executes them in its own context.

It (very) basically looks like this:

const file = process.argv[2];

require('fs').readFile(
    file,
    'utf-8',
    (error, data) => {
        eval(data);
    }
);

This is all working fine but I do not like mixing my server context with a test context. How can nodejs execute javascript code in a totally separate context?

Ideally, it would be something like this:

other_context.eval(data);

Many thanks for your help!

Upvotes: 3

Views: 1967

Answers (2)

zero298
zero298

Reputation: 26877

There are multiple ways of doing this. The easiest thing that you could try right now is to replace the file read with child_process#fork().

This means you are running in a totally separate process which is good and that you don't need eval() which is also very good.

Essentially:

const {
  fork
} = require('child_process');

const child = fork(file);
child.on("message", m => console.log(m));

The main thing is to get the code that you are testing out of the server. I just think terrible things can happen if you leave it that way.

Another option that is too broad to cover is to leverage Docker. That way, the code that gets executed is not only in another process, it's (and this is painting really broadly) practically on another computer.

Upvotes: 2

tne
tne

Reputation: 7261

isolated-vm might fit the bill for you.

isolated-vm is a library for nodejs which gives you access to v8's Isolate interface. This allows you to create JavaScript environments which are completely isolated from each other. You might find this module useful if you need to run some untrusted code in a secure way. You may also find this module useful if you need to run some JavaScript simultaneously in multiple threads. You may find this project very useful if you need to do both at the same time!

Upvotes: 3

Related Questions