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(‘顺利关闭‘)
});
});
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 31 32 37 2e 30 2e 30 2e 31 20 20 20 6c 6f 63 61 6c 68 6f 73 74 20 6c 6f 63 61 6c 68 6f 73 74 2e 6c 6f 63 61 6c 64 6f 6d 61 69 6e 20 6c 6f 63 61 6c 68 ... 146 more bytes>
缓冲区内容解读后: 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 coldspring.net taizhouwu.net mydb.net
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
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
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
原文:https://www.cnblogs.com/saintdingspage/p/11408535.html