读文件:
const fs=require('fs'); fs.readFile('./32_readfile.js','utf8',(err,data)=>{ if(err) throw err; console.log(data); }); const data=fs.readFileSync('./32_readfile.js','utf8'); // 同步 console.log(data); // 输出文件内容
写文件:
const fs=require('fs'); const content=Buffer.from('this is a test'); fs.writeFile('./text',content,err=>{ if(err) throw err console.log('done!'); }) fs.writeFile('./text2','this is a test2',{encoding:'utf8'},err=>{ if(err) throw err console.log('done!'); })
获取文件信息 stat:
const fs=require('fs'); fs.stat('./34_stat.js',(err,stats)=>{ if(err) { console.log('文件不存在') }; console.log(stats.isFile()); console.log(stats.isDirectory()); console.log(stats); }); true false Stats { dev: 637858, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: undefined, ino: 23925373020527024, size: 200, blocks: undefined, atimeMs: 1561992748290, mtimeMs: 1561992948768.0908, ctimeMs: 1561992948768.0908, birthtimeMs: 1561992748290.0913, atime: 2019-07-01T14:52:28.290Z, mtime: 2019-07-01T14:55:48.768Z, ctime: 2019-07-01T14:55:48.768Z, birthtime: 2019-07-01T14:52:28.290Z }
重命名:
const fs=require('fs'); fs.rename('./text','test.txt',err=>{ if(err) console.log('文件不存在'); })
删除:
const fs=require('fs'); fs.unlink('./test.txt',err=>{ if(err) throw err; console.log('done'); })
读文件夹:
const fs=require('fs'); fs.readdir('./',(err,data)=>{ if(err) throw err; console.log(data); })
创建文件夹:
const fs=require('fs'); fs.mkdir('text',err=>{ if(err) throw err; console.log('done'); })
删除文件夹:
const fs=require('fs'); fs.rmdir('text',err=>{ if(err) throw err; console.log('done'); })
监视:
const fs=require('fs'); fs.watch('./',{ recursive:true // 是否递归(子文件夹) },(eventType,filename)=>{ // eventType:变化类型 console.log(eventType,filename); })
读流:比如播放电影,512的内存也可以播放2G的电影,就是通过流一点点读数据
const fs=require('fs');
const rs=fs.createReadStream('./41_readstream.js');
rs.pipe(process.stdout); // 控制台
写:
const fs=require('fs');
const ws=fs.createWriteStream('./test.txt');
const tid=setInterval(()=>{
const num=parseInt(Math.random()*10);
if(num<7){
ws.write(String(num));
}else{
clearInterval(tid);
ws.end();
}
});
ws.on('finish',()=>{
console.log('done');
})
解决回调地狱:promisify
const fs=require('fs'); const promisify=require('util').promisify; const read=promisify(fs.readFile); // 第一种 read('./43_promisify.js').then(data=>{ console.log(data.toString()); }).catch(ex=>{ console.log(ex); }); // 第二种 async