带有socket.io的nodejs中的UTF-8

我无法通过使用nodejs和socket.io将utf-8编码的string传递给客户端。 我使用的是什么传输(websocket,flashsocket或者xhr-polling)似乎并不重要。

代码非常简单明了:

服务器:

var app = require('http').createServer(handler) , io = require('socket.io').listen(app,{log:false}); app.listen(80); function handler (req, res) { fs.readFile(__dirname + '/index.html','utf-8', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } var type="text/html"; res.writeHead(200, {'Content-Type':type + "; charset=utf-8"}); res.end(data,'utf8'); }); } io.sockets.on('connection', function (socket) { socket.emit('msg', { text: 'æøå' });//Here we send the utf-8 characters to the client }); 

客户:

 <!Doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta charset=utf-8 /> <script type="text/javascript" src="http://192.168.0.12/socket.io/socket.io.js" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> window.WEB_SOCKET_SWF_LOCATION = 'http://192.168.0.12/socket.io/static/flashsocket/WebSocketMain.swf'; var socket = io.connect('http://192.168.0.12'); socket.on('msg', function(data){alert(data.text);}); //here the data is recieved and put into the alert box ... ... 

看起来像这样的数据总是UTF-8双重编码: 客户端警报与来自nodejs服务器的数据

我正在使用nodejs 0.8.17和socket.io 0.9

您的node.js文件(代码的第一个片段)不是以UTF-8编码保存的,node.js期望文件以UTF-8格式保存。 这取决于你的文本编辑器,但通常当你保存一个文件,你应该能够select一个编码。