1

When i try to run my JS file i get this error:

http.js:783
    throw new TypeError('first argument must be a string or Buffer');

I was following this tutorial which didn't seem to mention the problem Tutorial Link

My JS file has:

var http = require('http'),
    fs = require('fs'),
    sanitize = require('validator').sanitize;

var app = http.createServer(function (request, response) {
    fs.readFile("client.html", 'utf-8', function (error, data) {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    });
}).listen(1337);

var io = require('socket.io').listen(app);

io.sockets.on('connection', function(socket) { 
    socket.on('message_to_server', function(data) { 
        var escaped_message = sanitize(data["message"]).escape();
        io.sockets.emit("message_to_client",{ message: escaped_message }); 
    });
});

I have Socket.io and validator installed in my node_modules folder. I'm quite new to this sort of stuff and looks like this tutorial wasn't a good starting choice, I can't seem to get it working.

Sir
  • 7,735
  • 12
  • 72
  • 138

1 Answers1

3

You're not doing any error checking, and I'd bet that readFile is throwing an error. This means data is undefined, so when you try to response.write(data), the http module throws an error.

Always check the error parameter in your callback functions, and handle it appropriately.

fs.readFile("client.html", 'utf-8', function (error, data) {
    if (error) {
        response.writeHead(500, {'Content-Type': 'text/html'});
        response.write(error.toString());
    } else {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
    }
    response.end();
});
josh3736
  • 124,335
  • 26
  • 203
  • 248
  • Ah i got a more useful error now `Error: ENOENT, open 'client.html'` – Sir Dec 10 '13 at 19:06
  • @Dave: `ENOENT` means the file cannot be found. – josh3736 Dec 10 '13 at 19:07
  • i know but see here: http://5.77.44.77/~civilian/socketio/ its definitely there =/ – Sir Dec 10 '13 at 19:08
  • Node probably isn't resolving paths how you expect. Paths are resolved relative to *the current working directory*, not where your script file is located. Try using [`__dirname`](http://nodejs.org/api/globals.html#globals_dirname) -- `__dirname + '/client.html'` – josh3736 Dec 10 '13 at 19:12
  • I've changed it not sure if it worked because when i ran the js file again i got `Error: listen EADDRINUSE`, i don't know how to free up the port to run it again. =/ – Sir Dec 10 '13 at 19:20
  • Kill the process listening to the port you're trying to use ([*nix](http://stackoverflow.com/q/9856590/201952)/[Windows](http://stackoverflow.com/q/48198/201952)), or use a different port. – josh3736 Dec 10 '13 at 19:23