node_vm2

A Python 3 to Node.js + vm2 binding, helps you execute JavaScript safely.

Also checkout node_vm2’s readme.

Functions

node_vm2.eval(code, **options)

A shortcut to eval JavaScript.

Parameters
  • code (str) – The code to be run.

  • options – Additional options sent to VM.__init__().

This function will create a VM, run the code, and return the result.

Classes

class node_vm2.BaseVM(server=None)

BaseVM class, containing some common methods for VMs.

Parameters

server (VMServer) – Optional. If provided, the VM will be created on the server. Otherwise, the VM will be created on a default server, which is started on the first creation of VMs.

__enter__()

This class can be used as a context manager, which automatically create() when entering the context.

__exit__(exc_type, exc_value, traceback)

See destroy()

create()

Create the VM.

destroy()

Destroy the VM.

class node_vm2.VM(code=None, server=None, **options)

VM class, represent vm2.VM.

Parameters
  • code (str) – Optional JavaScript code to run after creating the VM. Useful to define some functions.

  • server (VMServer) – Optional VMServer. See BaseVM for details.

  • options – The options for vm2.VM.

run(code)

Execute JavaScript and return the result.

If the server responses an error, a VMError will be raised.

call(function_name, *args)

Call a function and return the result.

Parameters
  • function_name (str) – The function to call.

  • args – Function arguments.

function_name can include “.” to call functions on an object. However, it is called like:

var func = vm.run("function.to.call");
return func(...args);

So this keyword might doesn’t work as expected.

class node_vm2.NodeVM(server=None, **options)

NodeVM class, represent vm2.NodeVM.

Parameters

If console="redirect", those console output will return as events, stored in an event queue, which could be accessed with event_que.

event_que = queue.Queue()

A queue.Queue object containing console events.

An event is a dict and you can get the text value with:

event = self.event_que.get()
text = event.get("value")
run(code, filename=None)

Run the code and return a NodeVMModule.

Parameters
  • code (str) – The code to be run. The code should look like a commonjs module (or an IIFE module, according to the options). See vm2.NodeVM for details.

  • filename (str) – Optional, used for stack trace. Currently this has no effect. (should vm-server send traceback back?)

Returns

NodeVMModule.

classmethod code(code, filename=None, **kwargs)

A class method helping you create a module in VM.

Parameters
  • code (str) – The code sent to run().

  • filename (str) – The filename sent to run().

  • kwargs – Other arguments are sent to constructor.

with NodeVM() as vm:
        module = vm.run(code)
        result = module.call_member("method")

vs.

with NodeVM.code(code) as module:
        result = module.call_member("method")
        # access the vm with `module.vm`
class node_vm2.NodeVMModule(id, vm)

Since we can only pass JSON between python and node, we use this wrapper to access the module created by NodeVM.run().

This class shouldn’t be initiated by users directly.

You can access the VM object with attribute NodeVMModule.vm.

__enter__()

This class can be used as a context manager. See NodeVM.code().

__exit__(exc_type, exc_value, tracback)

Destroy the VM if:

  1. This method is called.

  2. The module is created by NodeVM.code().

call(*args)

Call the module, in case that the module itself is a function.

get()

Return the module, in case that the module itself is json-encodable.

call_member(member, *args)

Call a function member.

Parameters
  • member (str) – Member’s name.

  • args – Function arguments.

get_member(member)

Return member value.

Parameters

member (str) – Member’s name.

destroy()

Destroy the module.

You don’t need this if you can just destroy the VM.

class node_vm2.VMServer(command=None)

VMServer class, represent vm-server. See start() for details.

Parameters

command (str) –

the command to spawn node process. If not set, it would use:

  1. Environment variable NODE_EXECUTABLE

  2. ”node”

__enter__()

This class can be used as a context manager, which automatically start() the server.

server = VMServer()
server.start()
# create VMs on the server...
server.close()

vs.

with VMServer() as server:
        # create VMs on the server...
__exit__(exc_type, exc_value, traceback)

See close().

start()

Spawn a Node.js subprocess and run vm-server.

vm-server is a REPL server, which allows us to connect to it with stdios. You can find the script at node_vm2/vm-server (Github).

Communication using JSON:

> {"id": 1, "action": "create", "type": "VM"}
{"id": 1, "status": "success"}

> {"id": 2, "action": "run", "code": "var a = 0; a += 10; a"}
{"id": 2, "status": "success", "value": 10}

> {"id": 3, "action": "xxx"}
{"id": 3, "status": "error", "error": "Unknown action: xxx"}

A VMError will be thrown if the node process cannot be spawned.

close()

Close the server. Once the server is closed, it can’t be re-open.