Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js vm module

Node.js vm module

Java FileNode.js Built-in Modules


Node.js's vm The module is JavaScript's virtual machine module; it allows you to compile and run code in a V8 virtual machine context. This module provides a way to execute JavaScript code in an isolated context, separated from the current process but using a specific context.

Main Features


Introduction to core APIs

The vm.Script class

vm.Script The class is used to compile code without running it, and the compiled script can be executed multiple times.

Example

const

vm

=

require

(

'vm'

)

;

const

script

=

new

vm.

Script

(

'x + y'

,

{

  filename

:

'add.vm'

,

  lineOffset

:

0

,

  displayErrors

:

true

}

)

;

Parameter Description

- `filename`: The file name used for stack traces - `lineOffset`: The line number offset of the script's first line - `columnOffset`: The column number offset of the script's first column - `displayErrors`: Whether to output errors to stderr when an error occurs - `timeout`: Execution timeout (in milliseconds) - `cachedData`: Contains optional V8 code cache data

vm.createContext([contextObject])

Creates a new context object, optionally initialized with an existing object.

Example

const

context

=

vm.

createContext

(

{

  x

:

10

,

  y

:

20

}

)

;

script.runInContext(contextifiedObject[, options])

Runs a compiled script in the specified context.

Example

const

result

=

script.

runInContext

(

context

)

;

console.

log

(

result

)

;

// Output 30


Use Cases

1. Securely execute untrusted code

Example

const

vm

=

require

(

'vm'

)

;

const

untrustedCode

=

`

  process.

exit

(

1

)

;

// Malicious code

`

;

try

{

 

const

script

=

new

vm.

Script

(

untrustedCode

)

;

 

const

context

=

vm.

createContext

(

{

}

)

;

  script.

runInContext

(

context

)

;

}

catch

(

err

)

{

  console.

log

(

'Security blocked:'

,

err.

message

)

;

}

2. Create an isolated test environment

Example

const

vm

=

require

(

'vm'

)

;

const

testCode

=

`

 

function

add

(

a

,

b

)

{

   

return

a

b

;

 

}

  add

(

2

,

3

)

;

`

;

const

context

=

vm.

createContext

(

{

}

)

;

const

result

=

vm.

runInContext

(

testCode

,

context

)

;

console.

log

(

'Test result:'

,

result

)

;

// Output 5

3. Template engine implementation

Example

const

vm

=

require

(

'vm'

)

;

function

render

(

template

,

data

)

{

 

const

code

=

\$

{

template

}

``

;

 

const

context

=

vm.

createContext

(

data

)

;

 

return

vm.

runInContext

(

code

,

context

)

;

}

const

template

=

'Hello, ${name}! You are ${age} years old.'

;

const

result

=

render

(

template

,

{

name

:

'Alice'

,

age

:

25

}

)

;

console.

log

(

result

)

;

// Output "Hello, Alice! You are 25 years old."


Security considerations

Although vm The module provides a certain degree of isolation, but it is not a completely secure sandbox:

  1. Scenarios where the file size is predictable and will not cause memory issues: Malicious code can still cause memory exhaustion
  2. Synchronous operations: An infinite loop can block the event loop
  3. Context escape: In some cases, global objects can be accessed

For scenarios that require higher security, consider:


Performance optimization tips

1. Reuse compiled scripts

Example

const

vm

=

require

(

'vm'

)

;

const

script

=

new

vm.

Script

(

'x * y'

)

;

// Execute the same compiled script multiple times

for

(

let i

=

0

;

i

<

100

;

i

++

)

{

 

const

context

=

vm.

createContext

(

{

x

:

i

,

y

:

2

}

)

;

  console.

log

(

script.

runInContext

(

context

)

)

;

}

2. Use cachedData to speed up compilation

Example

const

vm

=

require

(

'vm'

)

;

// Compile for the first time and obtain the cache data

const

script1

=

new

vm.

Script

(

'x + y'

)

;

const

cachedData

=

script1.

createCachedData

(

)

;

// Use the cache data later to speed up compilation

const

script2

=

new

vm.

Script

(

'x + y'

,

{

cachedData

}

)

;

3. Set timeout appropriately

Example

const

script

=

new

vm.

Script

(

'while(true) {}'

,

{

timeout

:

100

}

)

;

try

{

  script.

runInContext

(

vm.

createContext

(

{

}

)

)

;

}

catch

(

err

)

{

  console.

log

(

'Execution timed out:'

,

err.

message

)

;

}


Differences from eval

Feature vm module eval
Execution environment Can create isolated contexts Uses the current scope
Safety Relatively high Lower
Performance Can be precompiled, with high efficiency for repeated execution Needs to be parsed every time
Debugging support Supports file name and line number mapping Not supported
Resource control Can set limits such as timeouts No control

Summary

Node.js's vm The module is a powerful tool, especially suited to scenarios that require isolated execution of JavaScript code. Although it is not a completely secure sandbox solution, it provides sufficient security isolation and performance optimization in many cases. When used correctly, it can greatly improve the security and flexibility of applications.

Java FileNode.js Built-in Modules