The Wayback Machine - https://web.archive.org/web/20240204231417/https://www.geeksforgeeks.org/node-js-vm-complete-reference/
Open In App
Related Articles

Node.js VM Complete Reference

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 28 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials