Node.js程序中的本地文件操作用法小结
Node最引以为傲的就是它有一个非常小的核心。有一些语言绑定了完整的POSIXAPI,而Node实现了尽可能少的绑定,并通过同步、异步或流API形式暴露他们。
这种方法意味着,操作系统中有一些非常方便的功能,需要在Node中重建。这是一个教你如何使用文件系统软件包的实用教程。
引用文件
与文件系统的交互很重要的一点是要指向正确的文件。由于NPM的包使用相对路径引用,所以你不能把路径写死在代码。有两个主要方式来以确保包能引用到正确的文件:
//使用`path.join()`而不是`+`确保Windows也能正常工作
constpath=require('path')
//找到基于调用点的相对路径,对于命令行程序(CLIapplications)非常实用
path.join(process.cwd(),'my-dynamic-file')
//或者
path.resolve('my-dynamic-file')
//基于一个文件找到另外一个文件
path.join(__dirname,'my-package-file')
读取文件
在节点中的异步读取文件的最简单方法就是使用流!下面是一个例子:
constpath=require('path')
constfs=require('fs')
//readafileandpipeittotheconsole
fs.createReadStream(path.join(__dirname,'my-file'))
.pipe(process.stdout)
创建文件
创建文件也并不是很难,这里有一个用node实现的cat命令:
constpath=require('path')
constfs=require('fs')
//cat./my-file>./my-other-file
fs.createReadStream(path.join(__dirname,'my-file'))
.pipe(fs.createWriteStream(path.join(__dirname,'./my-other-file')))
删除文件
在Shell脚本中删除的文件和目录通常使用rm-rf命令。NodeJS中一个rimraf也实现了相同的功能:
constrimraf=require('rimraf')
constpath=require('path')
rimraf(path.join(__dirname,'./my-directory'),err=>{
if(err)throwerr
})
创建目录
创建跟删除文件很相似,使用mkdirp包
constmkdirp=require('mkdirp')
constpath=require('path')
mkdirp(path.join(__dirname,'foo/bar'),err=>{
if(err)throwerr
})
查找文件
使用readdirp查找当前目录下的文件:
constreaddirp=require('readdirp')
constjson=require('JSONStream')
constpath=require('path')
//recursivelyprintoutallfilesinallsubdirectories
//tothecommandline.Theobjectstreammustbe
//stringifiedbeforebeingpassedto`stdout`.
readdirp({root:path.join(__dirname)})
.pipe(json.stringify())
.pipe(process.stdout)
使用findup查找当前父级目录中的文件:
constfindup=require('findup')
constpath=require('path')
//recurseupallfilesrelativeto__dirnameandfind
//all`package.json`files.
findup(path.join(__dirname),'package.json',(err,res)=>{
if(err)throwerr
console.log('diris:'+res)
})
关于管道(pipes)
在管道中对整个数据流的错误进行一次处理非常。而不用对每个单独的数据流使用.on('error',cb):
constpump=require('pump')
constfs=require('fs')
//ohno,noerrorsarehandled!
fs.createReadStream('./in.file').pipe(fs.createWriteStream('./out.file'))
//that'sbetter,we'rehandingerrorsnow
constrs=fs.createReadStream('./in.file')
constws=fs.createWriteStream('./out.file')
pump(rs,ws,err=>{
if(err)throwerr
})