Skip to content

Commit 0389df9

Browse files
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, nodejs#4955 PR-URL: nodejs#5323 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Stephen Belanger <[email protected]> Reviewed-By: Myles Borins <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]>
1 parent ca7ac38 commit 0389df9

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

doc/api/vm.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,39 @@ e.g. `(0,eval)('code')`. However, it also has the following additional options:
304304
- `timeout`: a number of milliseconds to execute `code` before terminating
305305
execution. If execution is terminated, an [`Error`][] will be thrown.
306306

307+
## Example: Run a Server within a VM
308+
309+
The context of `.runInThisContext()` refers to the V8 context. The code passed
310+
to this VM context will have it's own isolated scope. To run a simple web server
311+
using the `http` module, for instance, the code passed to the context must either
312+
call `require('http')` on its own, or have a reference to the `http` module passed
313+
to it. For instance:
314+
315+
```js
316+
'use strict';
317+
const vm = require('vm');
318+
319+
let code =
320+
`(function(require) {
321+
322+
const http = require('http');
323+
324+
http.createServer( (request, response) => {
325+
response.writeHead(200, {'Content-Type': 'text/plain'});
326+
response.end('Hello World\\n');
327+
}).listen(8124);
328+
329+
console.log('Server running at http://127.0.0.1:8124/');
330+
})`;
331+
332+
vm.runInThisContext(code)(require);
333+
```
334+
335+
_Note: `require()` in the above case shares the state with context it is passed
336+
from. This might introduce risks when unknown code is executed, e.g. altering
337+
objects from the calling thread's context in unwanted ways. It is advisable to
338+
run `vm` code in a separate process._
339+
307340
[indirect `eval()` call]: https://es5.github.io/#x10.4.2
308341
[global object]: https://es5.github.io/#x15.1
309342
[`Error`]: errors.html#errors_class_error

0 commit comments

Comments
 (0)