2013-04-02 115 views
4

我是node.js的新手。尝试让请求结束时打印控制台。我尝试去localhost:8080和localhost:8080 /但没有在终端打印。任何想法为什么?这样做是因为当我运行此示例时,因为当我尝试在http://tutorialzine.com/2012/08/nodejs-drawing-game/上运行演示时,终端说socket已启动,但它不会呈现index.html页面。所以我不明白为什么这个代码服务于其他静态文件的代码不适合我。Node.js简单服务器请求结束事件问题

var static = require('node-static'); 

// 
// Create a node-static server instance to serve the './public' folder 
// 
// var file = new(static.Server)('./'); 

require('http').createServer(function (request, response) { 
    request.addListener('end', function() { 
     console.log("ended"); 
    }); 
}).listen(8080); 
+0

注:该教程是为快速2.X写的,其中'app'是的'http.Server'一个实例。对于Express 3.x,'app'是一个'function',所以你不能简单地'listen()'。查看[2.x至3.x迁移指南](https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x),特别是[Socket。 IO兼容性](https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x#socketio-compatibility)。 –

回答

0

你应该调用节点静态服务请求处理程序中,这样就可以得到index.html

var static = require('node-static'); 
var fileServer = new static.Server('./'); 

require('http').createServer(function (request, response) { 
    fileServer.serve(request, response); //add this line 
    request.addListener('end', function() { 
     console.log("ended"); 
    }); 
}).listen(8080); 
7

看来你是如何使用Node.js 0.10.x,并在新版本中你要恢复可读流,使它们发出事件:

require('http').createServer(function (request, response) { 
    var body = ''; 
    request.setEncoding('utf8'); 
    request.on('readable', function() { 
     body+= this.read(); 
    } 
    request.on('end', function() { 
     console.log('ended'); 
     console.log('Body: ' + body); 
    }); 
    request.resume(); 
}).listen(8080); 
+2

这对我来说伎俩,我的系统升级到最新的node.js版本,突然我的node.js应用程序被borked。 :/ –

+0

@NickJennings,还有必要侦听“可读”事件来读取数据,添加到答案中 – micnic