将中文转为unicode其实nodejs自带的模块就可以实现了。要实现转GB2312要借助iconv-lite模块。 转Uincode: var unicode = new Buffer(msg, ‘uCS2’); var unicodeHex = ""; for (var i = 0; i < unicode.length; i = i + 2) { unicodeHex += utils.toHex(unicode[i]) + utils.toHex(unicode[i + 1]); }
转为GB2312:
//将中文转化为GB2312 function chinese2Gb2312(data) { var gb2312 = iconv.encode(data.toString(‘UCS2’), ‘GB2312’); var gb2312Hex = ""; for (var i = 0; i < gb2312.length; ++i) { gb2312Hex += utils.toHex(gb2312[i]); } return gb2312Hex; }
注意js文件要保存为uft-8格式。不然结果是不对的
exports.pad = function (number, length, pos) { var str = “” + number; while (str.length < length) { //向右边补0 if (“r” == pos) { str = str + "0"; } else { str = “0” + str; } } return str; }
exports.toHex = function (chr, padLen) { if (null == padLen) { padLen = 2; } return this.pad(chr.toString(16), padLen); }