【nodejs】 文件系统(fs) 之读写文件
2015-06-30 18:37
706 查看
//写入文件 var data = "hello world"; fs.writeFile('c:\\a.txt', data, 'ascii', function(err) { if (err) { console.log('写入文件失败'); } else { console.log('保存成功, 赶紧去看看乱码吧'); } }); //读取文件 fs.readFile('c:\\a.txt', 'ascii', function(err, data) { if (err) { console.log('写入文件失败'); } else { console.log(data); } }); //[注意:默认情况下,数据编码为utf8;mode=438 ;flag=w]
如果有中文呢?
由于Node.js仅支持如下编码:utf8, ucs2, ascii, binary, base64, hex,并不支持中文GBK或GB2312之类的编码,
因此如果要读写GBK或GB2312格式的文件的中文内容,必须要用额外的模块:iconv-lite
1、安装模块:npm install iconv-lite
windows平台不支持npm 先解决这个问题
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
C:\Windows\system32>node -v
v0.12.5
C:\Windows\system32>npm -v
2.11.2
C:\Windows\system32>
ok 成功!
=========================
加载的文件必须是GB2312格式的
var iconv = require('iconv-lite'); var fs = require("fs") ; fs.readFile("c:\\v.txt",function (error,data){ if(error){throw error} ; var str = iconv.decode(data, 'GB2312'); console.log(str); }) ;
utf-8的文件如下
var fs = require("fs") ; fs.readFile("bb.txt","utf8",function (error,data){ if(error) throw error ; console.log(data) ; }) ;
相关文章推荐
- java.io.FileNotFoundException: /home/hadoop/hadoop/dfs/namenode/current/VERSION (Permission denied)
- 【nodejs】关于 alert 和 document
- Cannot install NodeJs: /usr/bin/env: node: No such file or directory
- node.js的开发学习
- Node.js学习开始了——事件流的控制/文件读写事件的的方法
- NodeJs学习笔记一(ubuntu下环境搭建)
- Leetcode42: Remove Nth Node From End of List
- nodejs导出excel的方法
- How to install 3 nodes Nutanix Cluster in one ESXi 6.0 Server
- 动态修改 NodeJS 程序中的变量值
- ENode框架Conference案例转载
- ENode框架Conference案例分析系列之 - 订单处理减库存的设计
- nodejs导出excel的方法
- LeetCode_Linked List_Swap Nodes in Pairs
- LeetCode-Count Complete Tree Nodes -解题报告
- nodejs socket error Error:read ECONNRESET
- nodejs 导出excel
- 解决 SVN Skipped 'xxx' -- Node remains in conflict
- Socket.IO 和 Node.js 入门
- 完全面向于初学者的Node.js指南