Reputation: 8277
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.
Upvotes: 1
Views: 5391
Reputation: 145102
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();
});
Upvotes: 3