为什么我的var无法访问?

时间:2011-08-03 10:09:41

标签: node.js

var http = require('http')
, io = require('socket.io')
, fs = require('fs')
, url = require('url')
, server;

server = http.createServer(function(request, response) {
  var pathname = url.parse(request.url).pathname;

  console.log("Request for: " + request.method + ' ' + pathname);
  switch(request.method + ' ' + pathname) {
    case 'POST /notify':
      var data = "";
      request.addListener('data', function(chunk) {
        data += chunk;
        console.log(data);
      });
      console.log(data);
      response.end();
      break;
    default:
      response.writeHead(404);
      response.end();
      break;
  };
});

server.listen(3526);

var io = io.listen(server);

io.sockets.on('connection', function (socket) {
  socket.emit('notifications', { demo: 'test' });
});

我知道这可能是一个愚蠢的问题,但为什么我不能访问request.AddListener块之外的 data 变量?

请提供解决方案。

1 个答案:

答案 0 :(得分:3)

因为Node一直在运行,当你到达第二个console.log数据时,没有填充。我添加了一个结束的监听器,以便它更好地工作

    server = http.createServer(function(request, response) {
      var pathname = url.parse(request.url).pathname;
      var data = "";
      console.log("Request for: " + request.method + ' ' + pathname);
      switch(request.method + ' ' + pathname) {
        case 'POST /notify':      
          request.addListener('data', function(chunk) {
            data += chunk;
            console.log('data1: '+data);
          });            
          break;
        default:
          response.writeHead(404);
          response.end();
          break;
      };
      request.addListener('end',function(){
        console.log('data2: '+data);
        response.end(data);
      });        
    });