由于在NodeJs平台上的缺乏对GBK编码的处理,对于国人来说比较郁闷,故而出现了a2u、iconv-lite等这样的GBK编码处理的模块。
a2u固然没有iconv-lite强大,不过如果你仅需要处理GBK编码的话,a2u是比iconv-lite更佳的选择,只因为其速度更快、性能更好。
用法
解码APIvar fs = require('fs');var buf = fs.readFileSync('demo.txt'); //txt's encoding is ANSI, the content is "I(我) love(爱) you(你)."var a2u = require('a2u');var str, newBuf;// Convert from an encoded buffer to js string.str = a2u.decode(buf);console.log(str);//I(我) love(爱) you(你).// If you want convert to buffer with ucs2 encoding, the second arg for method(decode) will be true.newBuf = a2u.decode(buf, true);console.log('ANSI buffer : ', buf);console.log('ucs2 buffer : ', newBuf);console.log(newBuf.toString('ucs2'));//I(我) love(爱) you(你).编码APIvar fs = require('fs');var a2u = require('a2u');var str = "I(我) love(爱) you(你).";var buf;// If stringbuf = a2u.encode(str);console.log('ANSI buffer : ', buf);// If bufferbuf = a2u.encode( new Buffer(str, 'ucs2') );console.log('ANSI buffer : ', buf);// Write to filefs.writeFileSync('ansi.txt', buf);
评论