Saturday 18 March 2017

What's the difference when passing the reference of require to runInContext and not?

In docs of vm module, is an example of Running an http server within a vm:

'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);

I am wondering why should we pass the require to the code inside the context? Is there a specific reason? In fact, I tried the following in node 6.10:

'use strict';
const vm = require('vm');

let code =
`(function() {

   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)(); 

and it works. Would the modification cause potential problem?

There is also a note in the doc, point out that share reference of require could introduce risk. To my understanding, the modified code is now safe, correct?



via minexu

No comments:

Post a Comment