NodeJS抛出新的TypeError
当我尝试运行我的JS文件,我得到这个错误:
http.js:783 throw new TypeError('first argument must be a string or Buffer');
我正在按照这个教程,似乎没有提到教程链接的问题
我的JS文件有:
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 }); }); });
我有我的node_modules文件夹中安装了Socket.io和validation程序。 我对这种东西很新,看起来这个教程不是一个好的开始select,我似乎无法得到它的工作。
你没有做任何错误检查,我敢打赌, readFile
抛出一个错误。 这意味着data
是未定义的,所以当你尝试response.write(data)
,http模块会抛出一个错误。
总是检查你的callback函数中的错误参数,并适当地处理它。
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(); });