Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: vm, run http server in vm by requiring #5323

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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