{
VM,
Script,
}
Create a virtual machine context.
Example usage
let vm = new VM({
"say": "Hello world",
});
Get or extend the context variables.
Example usage
let vm = new VM({
"say": "Hello world",
});
vm.context()
// { say: "Hello world" }
vm.context({ say: undefined, name: "Agent Smith" });
// { name: "Agent Smith" }
Run the given code in this VM's context.
- When
code
is a function,input_args
are passed to that function.
Example usage
let vm = new VM({
square ( n ) {
return n**2;
}
});
vm.run(`square( 2 );`)
Create a pre-compiled script.
Example usage
let script = new Script(`square( 2 )`);
Code input can be a function, string, or instance of vm.Script
.
- When
code
is a function,input_args
are passed to that function.
let ctx = {
square (n) {
return n**2;
},
};
let script = new Script( (num) => {
return square( num );
});
let result = script.run( ctx, 2 );
// 4
let script = new Script(`square( 2 )`);
import vm from 'vm';
let vm_script = new vm.Script(`square( 2 )`);
let script = new Script( vm_script );
Get the underlying instance of vm.Script
.
Run this Script's code using the given context.
ctx
- (required) can be an instance ofVM
or an objectdefault_ctx
is applied, thenctx
Example usage
let script = new Script(`square( 2 )`);
script.run({
square ( n ) {
return n**2;
}
});