Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js VM Complete Reference

Improve Article
Save Article
  • Last Updated : 28 Feb, 2023
Improve Article
Save Article

The VM module enables compiling and running code within V8 Virtual Machine contexts.

Example:

Javascript




// Node.js program to demonstrate the    
// script.runInContext() method
  
// Including util and vm module
const util = require('util');
const vm = require('vm');
  
// Constructing context
const contextobj = {
name: 'Nidhi',
articles: 60
};
  
// Constructing script
const script = new vm.Script('articles *= 10;');
  
// Contextifying object
vm.createContext(contextobj);
  
// Calling runInContext method
script.runInContext(contextobj);
  
// Displays output
console.log(contextobj);

Output:

{ name: 'Nidhi', articles: 600 }

The Complete list of VM are listed below:

Class: vm.Script

Class: vm.Script

Description

new vm.Script()Creates a new vm.Script object
script.createCachedData()It can be used with the cachedData option of the script constructor.
script.runInContext()Run the compiled code which is present inside the vm.Script object 
script.runInNewContext()First contextifies the stated contextObject, runs the compiled code inside the vm
script.runInThisContext()Runs the compiled code present inside the vm.Script within the context 

VM Methods

VM Methods

Description

vm.createContext() Create a single context that can be utilized to run more than one scripts.
vm.runInThisContext()Runs it inside the context of the current global and then returns the output.
vm.isContext()Check if the stated object is being contextified using vm.createContext() method or not.
vm.runInContext()It runs the code inside the context of the contextifiedObject and then returns the output.
vm.runInNewContext()Compiles the code written and runs 
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!