项目中好多后台文件处理代码要自己写,记录一下常用库啦~
一、fs文件读写库,最常用的api有
(1)readdirSync(path)同步读取文件夹,返回path下所有文件名
(2)readFileSync(path,'utf-8')同步读取文件,返回读取的文件内容
(3)fs.statSync( path, options )它返回一个Stats对象,其中包含文件路径的详细信息
来个自己写的递归找目标文件夹的例子:
/*递归读取dir寻找所有目标文件夹,返回储所找到的所有含有目标文件夹的目录的数组
dir:要搜索的目录
dist:要寻找的目标文件夹名
arr:存储含有目标文件夹的目录
*/
finddir(dir,dist,arr) {
const mydir = typeof arr != "object" ? [arr] : arr;
const files = fs.readdirSync(dir);
files.forEach((item) => {
if (item == dist) {
let path = dir + "/" + item;
mydir.push(path);
}
let filepath1 = dir + "/" + item;
let stat = fs.statSync(filepath1);
if (stat.isDirectory()) {
this.readi18ndir(filepath1, mydir, dist);
}
});
return mydir;
}
二、fs-extra模块是fs模块的扩展,提供了更多便利的 API,并继承了fs模块的 API
(1)ensureDir (path)创建目录:promise风格异步。确保目录的存在,如果目录结构不存在,就创建一个,可创建多层目录,无需一层一层创建。
(2)copy(src, dest)复制文件:promise风格异步,默认覆盖现有的文件或目录,可复制单个文件也可复制整个文件夹
(3)remove(path)删除文件:promise风格异步,可删除文件或文件夹,文件夹不必为空,可删除文件夹中所有的内容。
接上一个例子,实现将目标文件夹中的指定文件复制到新文件夹:
/*组装目录,并复制文件
dirname:组装目录的最外层文件夹名称
dist:递归搜寻的目标文件夹名
*/
async formCatalog(dirname, dist) {
//寻找所有含有我要找的文件夹的目录
const mydirs = this.finddir(this.rootPath1,dist,[]);
//创建组装目录的最外层文件夹
let copyRoot = path.join(this.rootPath2, dirname);
await fsExtra.ensureDir(copyRoot);
const dir = [];
const paths = [];
const newdirs = [];
for (let i = 0; i < mydirs.length; i++) {
//这四部操作都是为了组装我要的目录结构
dir[i] = mydirs[i].split("/");
dir[i].splice(0, 1);
paths[i] = dir[i].join("/");
newdirs[i] = path.join(copyRoot, paths[i]);
//确保存在这个目录结构
await fsExtra.ensureDir(newdirs[i]);
//把另一个文件夹中的文件复制到新组装的这个目录里面
await fsExtra.copy(
path.join(mydirs[i].replace(/\\/g, "/"), "/"),
newdirs[i]
);
}
return newdirs;
}
三、path提供了一些用于处理文件路径的api,最常用的就是path.join(),可将多个字符串连接成路径。该方法的主要用途在于,会正确使用当前系统的路径分隔符,Unix系统是"/",Windows系统是"\"。
四、compressing提供一些用于文件压缩的api,当前支持tar、gzip、tgz、zip格式。
(1)压缩文件,promise风格
compressing.gzip.compressFile('file/path/to/compress', 'path/to/destination.gz')
.then(compressDone)
.catch(handleError);
(2)压缩文件夹,promise风格,gzip仅支持压缩单个文件,应用tgz格式代替。
compressing.tar.compressDir('dir/path/to/compress', 'path/to/destination.tar')
.then(compressDone)
.catch(handleError);