Node.js读写中文内容文件操作

来源:互联网 发布:linux看b站 编辑:程序博客网 时间:2024/04/29 06:02

由于Node.js仅支持如下编码:utf8, ucs2, ascii, binary, base64, hex,并不支持中文GBK或GB2312之类的编码,

因此如果要读写GBK或GB2312格式的文件的中文内容,必须要用额外的模块:iconv-lite


1、安装模块:npm install iconv-lite

2、演示代码,把下面的代码复制到一个文件中,假设是ch.js(注意:js文件必须保存为utf8编码格式):

// 加载File System读写模块var fs = require('fs');// 加载编码转换模块var iconv = require('iconv-lite'); var file = "c:\\a.txt";writeFile(file);readFile(file);function writeFile(file){    // 测试用的中文    var str = "\r\n我是一个人Hello myself!";    // 把中文转换成字节数组    var arr = iconv.encode(str, 'gbk');    console.log(arr);        // appendFile,如果文件不存在,会自动创建新文件    // 如果用writeFile,那么会删除旧文件,直接写新文件    fs.appendFile(file, arr, function(err){        if(err)            console.log("fail " + err);        else            console.log("写入文件ok");    });}function readFile(file){    fs.readFile(file, function(err, data){        if(err)            console.log("读取文件fail " + err);        else{            // 读取成功时            // 输出字节数组            console.log(data);            // 把数组转换为gbk中文            var str = iconv.decode(data, 'gbk');            console.log(str);        }    });}

3、用node.exe执行这个js文件,结果如下:

C:\>node ch.js<Buffer 0d 0a ce d2 ca c7 d2 bb b8 f6 c8 cb 48 65 6c 6c 6f 20 6d 79 73 65 6c 66 21>写入文件ok<Buffer 0d 0a ce d2 ca c7 d2 bb b8 f6 c8 cb 48 65 6c 6c 6f 20 6d 79 73 65 6c 66 21>我是一个人Hello myself!C:\>

注1:Node的iconv模块,仅支持linux,不支持Windows,因此要用纯js的iconv-lite,另:作者说iconv-lite的性能更好,具体参考git站点:iconv-lite

注2:我在测试读写文件时,始终无法把中文写入文件,一直乱码,读取正常,后来同事帮我发现:js文件的编码格式是ansi,nodejs的代码文件必须是utf8格式

注3:如果程序操作的文件,都是以UTF8编码格式保存的,那么就不需要使用iconv模块,直接以utf8格式读取文件即可,如:

// 参数file,必须保存为utf8格式,否则里面的中文会乱码function readFile(file){    // readFile的第2个参数表示读取编码格式,如果未传递这个参数,表示返回Buffer字节数组    fs.readFile(file, "utf8", function(err, data){        if(err)            console.log("读取文件fail " + err);        else{            // 读取成功时            console.log(data);// 直接输出中文字符串了        }    });}

结论:使用node.js开发时,无论是代码文件,还是要读写的其它文件,都建议使用UTF8编码格式保存,这样可以无需额外的模块支持

5 0
原创粉丝点击