Skip to content

Commit f0edf87

Browse files
eljefedelrodeodeljefeMyles Borins
authored and
Myles Borins
committed
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: #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 b21d145 commit f0edf87

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

doc/api/vm.md

+33
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,39 @@ e.g. `(0,eval)('code')`. However, it also has the following additional options:
297297
- `timeout`: a number of milliseconds to execute `code` before terminating
298298
execution. If execution is terminated, an [`Error`][] will be thrown.
299299

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

0 commit comments

Comments
 (0)