diff --git a/doc/api/vm.md b/doc/api/vm.md index 4cccc12378631e..d53c8dc8d70850 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -297,6 +297,39 @@ e.g. `(0,eval)('code')`. However, it also has the following additional options: - `timeout`: a number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. +## Example: Run a Server within a VM + +The context of `.runInThisContext()` refers to the V8 context. The code passed +to this VM context will have it's own isolated scope. To run a simple web server +using the `http` module, for instance, the code passed to the context must either +call `require('http')` on its own, or have a reference to the `http` module passed +to it. For instance: + +```js +'use strict'; +const vm = require('vm'); + +let code = +`(function(require) { + + const http = require('http'); + + http.createServer( (request, response) => { + response.writeHead(200, {'Content-Type': 'text/plain'}); + response.end('Hello World\\n'); + }).listen(8124); + + console.log('Server running at http://127.0.0.1:8124/'); + })`; + + vm.runInThisContext(code)(require); + ``` + +_Note: `require()` in the above case shares the state with context it is passed +from. This might introduce risks when unknown code is executed, e.g. altering +objects from the calling thread's context in unwanted ways. It is advisable to +run `vm` code in a separate process._ + [indirect `eval()` call]: https://es5.github.io/#x10.4.2 [global object]: https://es5.github.io/#x15.1 [`Error`]: errors.html#errors_class_error