4

I'm new to node.js. Trying to get a console to print when the request ends. I try to go to localhost:8080 and also localhost:8080/ but nothing prints in the terminal. Any idea why? Doing this because when I run this example because when I try to run the demo at http://tutorialzine.com/2012/08/nodejs-drawing-game/ the terminal says socket started but it does not render the index.html page. So I can't figure out why this code to serve static files for other is not working for me.

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);
Ben Scheib
  • 392
  • 1
  • 3
  • 16
  • Note: That tutorial was written for Express 2.x, in which `app` was an instance of `http.Server`. With Express 3.x, `app` is instead a `function` so you can't simply `listen()` to it. Have a look through the [2.x to 3.x migration guide](https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x), especially [Socket.IO compatibility](https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x#socketio-compatibility). – Jonathan Lonowski Apr 02 '13 at 03:34

2 Answers2

7

It seems that your are using Node.js 0.10.x and in the new version you have to resume the readable streams to make them emit events:

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);
micnic
  • 10,915
  • 5
  • 44
  • 55
  • 2
    This did the trick for me, my system upgraded to the latest node.js version and suddenly my node.js apps were borked. :/ – Nick Jennings Apr 10 '13 at 11:02
  • @NickJennings, also it is necessary to listen for `readable` event to read data, added to the answer – micnic Apr 10 '13 at 12:52
0

You should be call node-static serve inside the request handler so that you can get 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);
user568109
  • 47,225
  • 17
  • 99
  • 123