【问题标题】:UTF-8 in nodejs with socket.io带有socket.io的nodejs中的UTF-8
【发布时间】:2013-01-19 10:27:32
【问题描述】:

我在使用 nodejs 和 socket.io 将 utf-8 编码的字符串传递给客户端时遇到问题。我使用什么传输(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 0.8.17 和 socket.io 0.9

【问题讨论】:

  • 你的 .js 文件以什么编码格式保存?
  • 都是 utf-8,如果我直接在其中添加 utf-8 编码字符(例如æøå),则索引文件在客户端上显示正常。似乎在使用 socket.io 的传输中发生了一些事情。
  • 请改用这个socket.emit('msg', { text: 'æøå'.charCodeAt(0).toString(16) });,有什么警告?
  • 这是什么? - 它输出“fffd”
  • @jornare 谢谢,问题现在很明显

标签: javascript node.js utf-8 character-encoding socket.io


【解决方案1】:

您的 node.js 文件(代码的第一个 sn-p)未以 UTF-8 编码保存,node.js 期望文件以 UTF-8 保存。这取决于您的文本编辑器,但通常当您保存文件时,您应该能够选择编码。

【讨论】:

  • 我以为我已经检查了两次,但显然 Zend Studio 欺骗了我:/谢谢!!
猜你喜欢
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 2018-05-02
  • 2011-06-29
  • 2014-04-13
相关资源
最近更新 更多