标签:conf sync connect console range ring 对象 buffer 缓冲区
fs.open(path,flags,[mode],callback)
fs.openSync(path,flags,[mode])
fs.close(fd,callback)
fs.closeSync(fd)
fs.open(‘myFile‘,‘w‘,function(err,fd){ if(!error){ fs.close(fd); } }
注意:回调函数被指定,并接收err和fd参数,fd参数是你可以用来读取或写入该文件的文件描述符。
fs.writeFile(path,data,[options],callback)
fs.writeFileSync(path,data,[options])
var fs=require(‘fs‘); var config={ maxFiles:20, maxConnections:15, rootPath:‘./routes‘ }; var configTxt=JSON.stringify(config); var options={ encoding:‘utf8‘, flag:‘w‘ }; fs.writeFile(‘config.text‘,configTxt,options,function(err){ if(err){ console.log(‘config write fail‘); } else{ console.log(‘config write success‘); } });
(2)同步和异步文件写入
fs.writeSync(fd,data,offset,length,position)
fs.write(fd,data,offset,length,position,callback)
var fs=require(‘fs‘); var fruitBow1=[‘apple‘,‘orange‘,‘banana‘]; function writeFruit(fd){ if(fruitBow1.length){ var fruit=fruitBow1.pop()+‘‘; fs.write(fd,fruit,null,null,function(err,bytes){ if(err){ console.log(‘File write failed.‘); }else{ console.log(‘write: %s %dbytes‘,fruit,bytes); writeFruit(fd); //反复调用,直到fruitBow1的length为0 } }); }else{ fs.close(fd); } } fs.open(‘fruit.txt‘,‘w‘,function(err,fd){ writeFruit(fd); });
fs.createWriteStream(path,[options])
var fs=require(‘fs‘); var grains=[‘wheat‘,‘rice‘,‘oats‘]; var options={encoding:‘utf8‘,flag:‘w‘}; var fileWriteStream=fs.createWriteStream(‘grains.txt‘,options); fileWriteStream.on(‘close‘,function(){ console.log(‘file closed.‘); }); while(grains.length){ var data=grains.pop()+‘ ‘; fileWriteStream.write(data); console.log(‘write: %s‘,data); } fileWriteStream.end();
fs.readFile(path,[options],callback)
fs.readFileSync(path,[options])
var fs=require(‘fs‘); var options={encoding:‘utf8‘,flag:‘r‘}; fs.readFile(‘config.txt‘,options,function(err,data){ if(err){ console.log(‘Failes to open config File.‘); }else{ console.log(‘config Loaded.‘); var config=JSON.parse(data); console.log(‘Max Files: ‘+config.maxFiles); console.log(‘maxConnections: ‘+config.maxConnections); console.log(‘rootPath: ‘+config.rootPath); } });
fs.readSync(fd,buffer,offset,length,position)
fs.read(d,buffer,offset,length,position,callback)
var fs=require(‘fs‘); var options={encoding:‘utf8‘,flag:‘r‘}; var fileReadStream=fs.createReadStream(‘grains.txt‘,options); fileReadStream.on(‘data‘,function(chunk){ console.log(‘Grains: %s‘,chunk); console.log(‘read %d bytes of data.‘,chunk.length); }); fileReadStream.on(‘close‘,function(){ console.log(‘file closed.‘); });
标签:conf sync connect console range ring 对象 buffer 缓冲区
原文地址:http://www.cnblogs.com/lyy-2016/p/6691285.html