Node.js VM Module

Here is a complete, clean, and easy-to-understand Node.js VM Module tutorial — perfect for your Node.js documentation series.


🚀 Node.js VM Module Tutorial

The VM (Virtual Machine) Module in Node.js allows you to:

✔ Run JavaScript code safely in sandboxes
✔ Execute untrusted code
✔ Create isolated contexts
✔ Build custom scripting engines
✔ Implement template engines
✔ Run code with controlled permissions

Built-in import:


The VM module is powerful but must be used carefully.


🧠 What is the VM Module?

The VM module lets you run JavaScript code inside:

  • Isolated contexts (sandbox)

  • New global scopes

  • Controlled environments

  • Virtualized V8 contexts

This is similar to eval() but much safer and more controlled.


🌐 1. Basic Example: Run Code in VM


 


🔒 2. Run Code in a Sandbox (Isolated Global)

Example with sandbox:


 

The code runs only inside sandbox, not in Node.js global scope.


🧱 3. Fully Isolated Execution


 


🕒 4. Run Code with Timeout or Memory Limit

Prevent infinite loops:


 

Prevent heavy memory usage:


🧩 5. vm.Script() — Precompiled Code

Useful when reusing same code multiple times.


 


🌐 6. Using runInNewContext()

Creates a brand new sandbox every time.


 


📦 7. Accessing Node.js in VM (Controlled)

You can expose only selected APIs:


 

By default, Node.js Globals are NOT exposed inside VM.


🚫 8. Prevent Access to Dangerous APIs

Restricting sandbox:


 


🧪 9. Using VM to Execute Dynamic User Code


 


🪟 10. vm.SourceTextModule – ES Module Support

Node.js VM supports ES module evaluation.


 


⚙️ 11. vm.Module — Advanced Module Loading

Used to create custom loaders.


 


📘 12. Summary of VM Module Features

FeatureDescription
runInNewContextRun code in isolated sandbox
runInContextReuse existing sandbox
runInThisContextRun in same global but isolated
vm.ScriptPrecompile and reuse JS code
vm.createContextCreate a sandbox
vm.ModuleCreate ES modules
timeoutRestrict runtime
cachedDataSpeed up script execution

🛡️ 13. When to Use VM Module

✔ Running untrusted code safely
✔ Sandboxed user scripting
✔ Custom JS engines
✔ Template engines
✔ Serverless-like environments
✔ Testing snippets
✔ Security-sensitive applications


🎉 Conclusion

Node.js VM Module is extremely powerful for:

  • Isolation

  • Security

  • Performance

  • Sandbox environments

  • Dynamic code evaluation

You can build advanced systems like:

  • Online code editors

  • Template engines

  • Automation tools

  • Custom interpreters

You may also like...