如何处理NodeJ中的多个并行请求

沙赫罗克

我正在使用PhantomJS在NodeJS中进行屏幕截图,但是它无法处理来自用户的多个请求。问题是当几个用户同时发送请求时,他们会得到相同的结果。

这是我正在使用的代码:

var http = require('http');
var phantom = require('phantom');
var url, img;
http.createServer(function(req, res) {
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.writeHeader(200, { "Content-Type": "text/html" });
  url = req.url;
  url = url.replace('/', '');
  url = url.trim();
  if (!(url == 'favicon.ico')) {
    console.log(url);
    phantom.create().then(function(ph) {
      ph.createPage().then(function(page) {
        page.property('viewportSize', { width: 1024, height: 768 }).then(function() {
          page.open('http://' + url + '/').then(function(status) {
            console.log(status);
            page.property('onLoadFinished').then(function() {
              if (!(status == 'success')) {
                res.write('<html><body><h2>' + status + ' : ' + url + ' is not correct url!</h2></body></html>');
                res.end();
                page.close();
              } else {
                setTimeout(function() {
                  page.renderBase64('jpeg').then(function(img) {
                    res.write('<html><body><img src="data:image/jpeg;base64,' + img + '"/></body></html>');
                    res.end();
                    page.close();
                  });
                }, 4000);
              }
            });
          });
        });
      });
    });
  }
}).listen(80, '127.0.0.1');
console.log('Server running at http://127.0.0.1:80/');
滞后反射

您已var url, img;http请求范围之外进行了定义,这意味着它们被不同的请求共享(一个请求可能会更改它,而前一个请求仍在处理它),这可能是导致问题的原因。将这些声明移到请求处理程序中:

// var url, img; // << move this
http.createServer(function(req, res) {
  var url, img; // << here
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.writeHeader(200, { "Content-Type": "text/html" });

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章