fs文件系统模块,这是一个非常重要的模块,对文件的操作都基于它。该模块的所有方法都有同步和异步两种方式,下面便介绍一下该模块的使用。
1、检测当前进程对文件的权限
使用fs.access(path[, mode], callback)
方法检查权限,mode参数是一个整数,有以下常量值:
使用如下所示:
fs.access('./note.txt',fs.constants.F_OK,(err)=>{console.log(err?'文件不存在':'文件已经存在');});
同步版本,如果发生异常,则直接抛出异常,否则什么也不做。同步版本可以利用try..catch来做,适用所有方法,如下所示:
try{fs.accessSync('./note.txt',fs.constants.F_OK);}catch(ex){console.log('文件不存在');}
2、获取文件状态
使用fs.stat(path, callback)
,fs.statSync(path)
方法来获取指定path的状性,callback有(err, stats)两个参数,stats是fs.stats对象,具有以下属性:
{ dev: 638212, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: undefined, ino: 105553116266564850, size: 1094, blocks: undefined, atime: 2016-11-22T08:45:43.505Z, mtime: 2016-11-22T09:33:13.535Z, ctime: 2016-11-22T09:33:13.535Z, birthtime: 2016-11-22T08:45:43.505Z }
还有以下方法:
stats.isFile() stats.isDirectory() stats.isBlockDevice() stats.isCharacterDevice() stats.isSymbolicLink() (only valid with fs.lstat()) stats.isFIFO() stats.isSocket()
使用如下所示:
fs.stat('./app.js',(err,stats)=>{ if(err) throw err; console.log(stats);});var stats = fs.statSync('../test.txt');//同步版本
3、文件追加
使用fs.appendFile(file, data[, options], callback)
方法向file写入数据,如果file不存在,则创建file,data参数为字符串或buffer,options可选参数是对象或字符串,具有以下属性:
使用如下所示:
fs.appendFile('./test.txt','hello world!/r/n',(err)=>{ if(err) throw err; console.log('写入成功');});//appendFile同步版本,返回值为undefinedfs.appendFileSync('./test.txt','hello nodejs!/r/n');
4、文件读取和写入
文件读取使用fs.readFile(file[, options], callback)
方法,参数含义如下:
新闻热点
疑难解答
图片精选