Skip to content

Commit

Permalink
doc: add vm example, be able to require modules
Browse files Browse the repository at this point in the history
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: #5323
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Myles Borins <myles.borins@gmail.com>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
  • Loading branch information
eljefedelrodeodeljefe authored and jasnell committed Apr 22, 2016
1 parent 40ede46 commit 6815a3b
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions doc/api/vm.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,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
Expand Down

0 comments on commit 6815a3b

Please sign in to comment.