1

我有一个带有 handleRequest 回调的 http 服务器,它在 vm.runInNewContext 中为每个请求运行另一个脚本。在 vm.runInNewContext 中运行的脚本会发出一些异步 http post 请求,并且只有在从帖子中获取响应后才会写入服务器响应。因此,handleRequest 回调的代码在写入服务器响应之前就结束了。安全吗?或者有没有办法避免这种情况?

这是一些代码:

var server = http.createServer(handleRequest);
server.listen(8080);

var handleRequest = function (request, response) {
    // get request data...

    var context = {
        ServerRequest : request,
        ServerResponse : response
     };

     var stringScript = // a string with the script that posts data
     var script = vm.createScript(stringScript);
     script.runInNewContext({ context: context });
}

脚本字符串这样做:

var request = require('request');
var options = {....}
var req = request.get(options);

    req.on('response', function (res) {
            var chunks = [];
            res.on('data', function(chunk) {
                chunks.push(chunk);
            });

            res.on('end', function() {
                var buffer = Buffer.concat(chunks);
                var encoding = res.headers['content-encoding'];
                if (encoding == 'gzip') {
                    zlib.gunzip(buffer, function(err, decoded) {
                        // set response headers and write the response
                        context.ServerResponse.end(decoded.toString()); 
                    });
                } else if (encoding == 'deflate') {
                    zlib.inflate(buffer, function(err, decoded) {
                    // set response headers and write the response                            
                    context.ServerResponse.end(decoded.toString());
                    })
                } else {
                    // set response headers and write the response                                                    
                    context.ServerResponse.end(buffer.toString());
                }
            });

    });
4

1 回答 1

0

简单的解决方案:从 VM 脚本返回一个承诺(例如使用Q-library )。
script.runInNewContext将返回您从 VM 脚本返回的任何内容。这样,当 VM 代码完成时,您就有一个“回调”。

// Script for VM
// I simplified it. Just resolve or reject the promise whenever you are done with your work
'use strict';

var defer = q.defer();

doABarrelRoll(function() {
  defer.resolve('RESULT');
});

defer.promise; // This line will return the promise.


从 VM 脚本返回值时,您不需要任何返回构造。只需写下你想要的东西,让魔法发生。

// Script for current context
'use strict';

var server = http.createServer(handleRequest);
server.listen(8080);

var handleRequest = function (request, response) {
  // get request data...

  var context = {
    ServerRequest : request,
    ServerResponse : response
  };

  var stringScript = // a string with the script that posts data
  var script = vm.createScript(stringScript);
  var prom = script.runInNewContext({
    context: context,
    q: require('q'),
  });

  prom.done(function ($result) {
    console.log('VM finished with result: ' + $result);
  });
}    
于 2015-08-18T08:40:49.740 回答