node.js中的fs.writeFileSync方法使用说明
方法说明:
同步版的fs.writeFile() 。
语法:
fs.writeFileSync(filename,data,[options])
由于该方法属于fs模块,使用前需要引入fs模块(varfs=require(“fs”))
接收参数:
filename (String) 文件名称
data (String|Buffer) 将要写入的内容,可以使字符串或buffer数据。
options (Object) option数组对象,包含:
·encoding (string) 可选值,默认‘utf8′,当data使buffer时,该值应该为ignored。
·mode (Number) 文件读写权限,默认值438
·flag (String) 默认值‘w'
例子:
fs.writeFileSync('message.txt','HelloNode');
源码:
fs.writeFileSync=function(path,data,options){
if(!options){
options={encoding:'utf8',mode:438/*=0666*/,flag:'w'};
}elseif(util.isString(options)){
options={encoding:options,mode:438,flag:'w'};
}elseif(!util.isObject(options)){
thrownewTypeError('Badarguments');
}
assertEncoding(options.encoding);
varflag=options.flag||'w';
varfd=fs.openSync(path,flag,options.mode);
if(!util.isBuffer(data)){
data=newBuffer(''+data,options.encoding||'utf8');
}
varwritten=0;
varlength=data.length;
varposition=/a/.test(flag)?null:0;
try{
while(written<length){
written+=fs.writeSync(fd,data,written,length-written,position);
position+=written;
}
}finally{
fs.closeSync(fd);
}
};