node.js中的fs.writeSync方法使用说明
方法说明:
同步版的fs.write()。写入文件(根据文件描述符)。
语法:
fs.writeSync(fd,buffer,offset,length[,position]) fs.writeSync(fd,data[,position[,encoding]])
由于该方法属于fs模块,使用前需要引入fs模块(varfs=require(“fs”))
接收参数:
fd 文件描述符。
buffer 缓冲区,数据将被写入。buffer尺寸的大小设置最好是8的倍数,效率较高。
offset buffer写入的偏移量
length (integer) 指定文件读取字节数长度
position (integer) 指定文件读取的起始位置,如果该项为null,将从当前文件指针的位置开始读取数据。
encoding (String) 字符编码
例子:
//fs.writeSync(fd,buffer,offset,length[,position])
varfs=require('fs');
fs.open('content.txt','a',function(err,fd){
if(err){
throwerr;
}
vardata='123123123helloworld';
varbuf=newBuffer(8);
fs.writeSync(fd,buf,0,8,0);
fs.close(fd,function(err){
if(err){
throwerr;
}
console.log('fileclosed');
})
})
//fs.writeSync(fd,data[,position[,encoding]])
varfs=require('fs');
fs.open('content.txt','a',function(err,fd){
if(err){
throwerr;
}
vardata='123123123helloworld';
fs.writeSync(fd,data,0,'utf-8');
fs.close(fd,function(err){
if(err){
throwerr;
}
console.log('fileclosed');
})
})
源码:
//usage:
//fs.writeSync(fd,buffer,offset,length[,position]);
//OR
//fs.writeSync(fd,string[,position[,encoding]]);
fs.writeSync=function(fd,buffer,offset,length,position){
if(util.isBuffer(buffer)){
if(util.isUndefined(position))
position=null;
returnbinding.writeBuffer(fd,buffer,offset,length,position);
}
if(!util.isString(buffer))
buffer+='';
if(util.isUndefined(offset))
offset=null;
returnbinding.writeString(fd,buffer,offset,length,position);
};