
正文
用node.js读写文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
node.js没有二进制数据类型,却提供了类似字节数组的“流“数据类型,着一种数据类型在文件系统模块中频频出现
- node.js打开文件
fs = require('fs');
console.log('准备打开文件');
fs.open('/etc/hosts','r+',function (err,fd) {
if (err)
{
console.log('damn~打开错误');
}
console.log('可以打开');
fs.close(fd,function (err) {
if (err)
{
console.error(err)
}
console.log('顺利关闭')
});
});
- 把文件内容读入缓冲区,并把缓冲区内容解读为utf8模式,(16进制也可以哦)
fs = require('fs');
fs.open('/etc/hosts','r+',function (err,fd) {
var mybuffer = Buffer.alloc(1024);
offset=0;
len = mybuffer.length;
fileposition = null;
fs.read(fd,mybuffer,offset,len,fileposition,function(err,readByte){
console.log("可读取数据数量"+readByte);
var wuwa=mybuffer.slice(0,readByte);
console.log("缓冲区内容解读前:",wuwa);
console.log("缓冲区内容解读后:",wuwa.toString('utf8'));
});
});
输出结果:
可读取数据数量196
缓冲区内容解读前: <Buffer 2e 2e 2e 6c 6f 6c 6f 6c 6f 6c 6f 2e 6c 6f 6c 6f 6d 6e 6c 6f 6c ... more bytes>
缓冲区内容解读后: 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 coldspring.net taizhouwu.net mydb.net
:: localhost localhost.localdomain localhost6 localhost6.localdomain6
- 异步读取(data仍为缓冲区)
fs = require('fs');
fs.readFile('/etc/hosts',function (err,data) {
if(err)
{
console.error(err);
}
console.log(data.toString('utf8'));#仍旧是buffer类型,需要转换为utf8类型
});
输出结果:
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
:: localhost localhost.localdomain localhost6 localhost6.localdomain6







