From f0edf87df15b0d1f2cb0c45403e11c6e55ba5fc8 Mon Sep 17 00:00:00 2001 From: Robert Jefe Lindstaedt Date: Thu, 21 Apr 2016 09:59:10 +0200 Subject: [PATCH] doc: add vm example, be able to require modules The intention behind is to present the user a way to execute code in a vm context. The current API doesn't allow this out-of-the-box, since it is neither passing a require function nor creating context with one. The missing docs for this behaviour have produced a number of Q&A items and have also been discussed in the node-archive repo. In both cases there was no real canonical answer. Refs: nodejs/node-v0.x-archive#9211, #4955 PR-URL: https://github.com/nodejs/node/pull/5323 Reviewed-By: James M Snell Reviewed-By: Stephen Belanger Reviewed-By: Myles Borins Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Benjamin Gruenbaum --- doc/api/vm.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) 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