| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 parent b21d145 commit f0edf87
1 file changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -297,6 +297,39 @@ e.g. `(0,eval)('code')`. However, it also has the following additional options: | |||
| 297 | 297 | - `timeout`: a number of milliseconds to execute `code` before terminating | |
| 298 | 298 | execution. If execution is terminated, an [`Error`][] will be thrown. | |
| 299 | 299 | ||
| 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 | + | ||
| 300 | 333 | [indirect `eval()` call]: https://es5.github.io/#x10.4.2 | |
| 301 | 334 | [global object]: https://es5.github.io/#x15.1 | |
| 302 | 335 | [`Error`]: errors.html#errors_class_error | |
| Back | FazBrowse Home | New Git URL |
0 commit comments