May 10, 2021 Node.js
2. vm.runInThisContext(code[, options])
3. vm.createContext([sandbox])
5. vm.runInContext(code, contextifiedSandbox[, options])
稳定性: 3 - 稳定
This section describes the .js (VM) module of nodes, which provides an API for compiling and running code in the context of v8 virtual machines.
The module can be accessed by:
var vm = require('vm');
JavaScript can be compiled immediately, saved, and then run.
vm.runInThisContext()
code
returns results for the parameter code.
The running code does not have access to the local scope, but it does have access to global objects.
Examples
vm.runInThisContext
and
eval
methods:
var localVar = 'initial value';
var vmResult = vm.runInThisContext('localVar = "vm";');
console.log('vmResult: ', vmResult);
console.log('localVar: ', localVar);
var evalResult = eval('localVar = "eval";');
console.log('evalResult: ', evalResult);
console.log('localVar: ', localVar);
// vmResult: 'vm', localVar: 'initial value'
// evalResult: 'eval', localVar: 'eval'
vm.runInThisContext
access the local scope, so it does not change
localVar
eval
has a local scope, so it changes
localVar
vm.runInThisContext
much like indirect
eval
(0,eval)('code')
However,
vm.runInThisContext
includes the following options:
filename
Allows you to change the file name that appears in the station traces.
displayErrors
Whether to print an error on stderr, the line of code that throws the exception is highlighted. S
yntax errors at compile time are caught, and errors thrown at execution time are caught.
True by
true
timeout
number of milliseconds that the code performed before the break.
If the execution terminates, an error is thrown.
If the
sandbox
is not empty, the context of the sandbox can be
script.runInContext
is called.
vm.runInContext
A script that runs this way,
sandbox
a global object that retains its own properties while having
built-in objects
and functions owned by a standard global object.
If the parameter sandbox object is empty, return a new and empty context-sensitive sandbox object that is available.
This function is useful for creating a sandbox that can run multiple scripts.
For example, when simulating a browser, you can use this function to create a sandbox that represents
<script>
put all the hashtags in the sandbox to execute.
Whether the sandbox object has been
vm.createContext
vm.runInContext
the code, runs on
contextifiedSandbox
the results. R
unning code does not have access to the local domain.
contextifiedSandbox
must be cultured up and down
vm.createContext
code
uses it through global variables.
vm.runInContext
vm.runInThisContext
are the same.
Compile and execute different scripts in the same context, for example:
var util = require('util');
var vm = require('vm');
var sandbox = { globalVar: 1 };
vm.createContext(sandbox);
for (var i = 0; i < 10; ++i) {
vm.runInContext('globalVar *= 2;', sandbox);
}
console.log(util.inspect(sandbox));
// { globalVar: 1024 }
Note that executing untrusted code requires skill and care.
vm.runInContext
but it's best to run untrusted code in a separate process if you want to be safe.
vm.runInNewContext
the code, and if sandbox is provided, the sandbox will be up and down the culture, otherwise a new up and down culture sandbox will be created, the sandbox will run the code as a global variable and return the results.
vm.runInNewContext
vm.runInThisContext
are the same.
Compile and execute the code, increase the value of the global variable, and set a new one. These global variables are contained in a new sandbox.
var util = require('util');
var vm = require('vm'),
var sandbox = {
animal: 'cat',
count: 2
};
vm.runInNewContext('count += 1; name = "kitty"', sandbox);
console.log(util.inspect(sandbox));
// { animal: 'cat', count: 3, name: 'kitty' }
Note that executing untrusted code requires skill and care.
vm.runInNewContext
but it's best to run untrusted code in a separate process if you want to be safe.
vm.runInDebugContext
and executes in the debug context of V8.
The main scenario is to gain access to V8 debug objects.
var Debug = vm.runInDebugContext('Debug');
Debug.scripts().forEach(function(script) { console.log(script.name); });
Note that the debug context and objects are internally bound to the debug implementation of V8 and may change (or remove) without warning.
--expose_debug_as=
by the --2000-switch.
Classes that contain precompiled scripts are executed in the specified sandbox.
Create a new script to compile the code, but it does not run. U
se the
vm.Script
to represent the compiled code. T
his code can be called multiple times using the following method. T
he returned script is not bound to any global variables.
Binding before running, release after execution.
The options for creating a script are:
filename
Allows you to change the file name that appears in the station traces.
displayErrors
Whether to print an error on stderr, the line of code that throws the exception is highlighted. O
nly syntax errors at compile time are caught, and errors thrown at execution time are controlled by the options of the script's methods.
True by
true
Similar
vm.runInThisContext
only a precompiled method for Script script objects.
Script
script.runInThisContext
the compiled script and returns the results.
The code being run does not have local scope access, but has access to global objects.
For the following example, the code is compiled once and run multiple times using
script.runInThisContext
var vm = require('vm');
global.globalVar = 0;
var script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
for (var i = 0; i < 1000; ++i) {
script.runInThisContext();
}
console.log(globalVar);
// 1000
The code options you are running:
displayErrors
Whether to print an error on stderr, the line of code that throws the exception is highlighted. O
nly applies to errors thrown at execution time.
You cannot create a Script instance with a
Script
error because the constructor throws.
timeout
number of milliseconds that the code performed before the break.
If the execution terminates, an error is thrown.
Similar
vm.runInContext
it is just a precompiled
Script
object method.
script.runInContext
the script
contextifiedSandbox
and returns the results.
The running code does not have access to the local domain.
script.runInContext
are similar
script.runInThisContext
Example: Compile a piece of code and execute it multiple times, which implements the self-addition of a global variable and creates a new global variable. These global variables are stored in a sandbox.
var util = require('util');
var vm = require('vm');
var sandbox = {
animal: 'cat',
count: 2
};
var script = new vm.Script('count += 1; name = "kitty"');
for (var i = 0; i < 10; ++i) {
script.runInContext(sandbox);
}
console.log(util.inspect(sandbox));
// { animal: 'cat', count: 12, name: 'kitty' }
Note that executing untrusted code requires skill and care.
script.runInContext
but for security, it's best to run untrusted code in a separate process.
Similar
vm.runInNewContext
it serves only as a precompiled
Script
object method.
If sandbox is provided then script.runInNewContext will sandbox up and down culture, if not provided, create a new up and down culture sandbox.
script.runInNewContext
script.runInThisContext
are similar.
Example: Compile code (set a global variable) and execute it multiple times in different contexts. These global variables are stored in a sandbox.
var util = require('util');
var vm = require('vm');
var sandboxes = [{}, {}, {}];
var script = new vm.Script('globalVar = "set"');
sandboxes.forEach(function (sandbox) {
script.runInNewContext(sandbox);
});
console.log(util.inspect(sandboxes));
// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
Note that executing untrusted code requires skill and care.
script.runInNewContext
but to be safe, it's best to run untrusted code in a separate process.