Open yaogengzhu opened 1 year ago
最近遇到一个需求,页面迁移,发现库的数据乱码 (数据库存在,gbk编码), 人麻了, 查表,更新表都需要转码 and 逆向
转码用到的第三方库有 iconv-lite
iconv-lite
const iconv = require("iconv-lite"); function toTransfromGbk(strUtf8) { let buffer = Buffer.from(strUtf8); const gbkString = iconv.encode(buffer, "gbk").toString("binary"); return gbkString; } function toTransUtf8(strGbk) { let buffer = Buffer.from(strGbk.toString(), "binary"); const utf8String = iconv.decode(buffer, "gbk"); return utf8String; }
查询demo
const res = await knex("xxx").select("*"); const newList = res.map((row) => { return Object.keys(row).reduce((object, key) => { if (row[key]) { if (["modify_time", "create_time", "update_time"].includes(key)) { object[key] = row[key]; } else { // let buffer = Buffer.from(row[key].toString(), "binary"); // const utf8String = iconv.decode(buffer, "gbk"); object[key] = toTransUtf8(row[key]); } } return object; }, {});
示例
let str = toTransfromGbk("合开"); let st1 = toTransUtf8("ÈÕ°²×°Á¿"); console.log(st1); console.log(str);
最近遇到一个需求,页面迁移,发现库的数据乱码 (数据库存在,gbk编码), 人麻了, 查表,更新表都需要转码 and 逆向
转码用到的第三方库有
iconv-lite
查询demo
示例