Reputation: 2893
I'm having trouble passing utf-8 encoded strings to the client using nodejs and socket.io. It does not seem to matter what transport (websocket, flashsocket or xhr-polling) I'm using.
The code is very plain and simple:
Server:
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
});
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
...
...
It seems like the data is always UTF-8 double encoded like this:
I'm using nodejs 0.8.17 and socket.io 0.9
Upvotes: 1
Views: 8620
Reputation: 140228
Your node.js file (the first snippet of code) is not saved in UTF-8 encoding, node.js expects files to be saved in UTF-8. This depends on your text editor but usually when you save a file, you should be able to choose an encoding.
Upvotes: 2