fs模块-删除文件-拷贝文件-目标目录扁平化

  封装一个npm包(operationDirectory),该包需暴露三个方法,第一个方法(removeDir参数为一个目标路径)实现删除目标目录下的所有文件及文件夹,第二个方法(copyDir参数为一个目标路径和一个输出路径)需实现拷贝目标目录的所有文件结构,第三个方法(flatDir参数为一个目标路径和一个输出路径)需要实现目标目录的扁平化展示,一个包暴露这三种方法;

 1 const fs = require('fs');
 2 let list = [];
 3 
 4 //实现删除目标目录下的所有文件及文件夹
 5 function removeDir(pathname) {
 6     if (fs.existsSync(pathname)) {
 7         if (fs.statSync(pathname).isDirectory()) {
 8             //如果是一个文件夹
 9             let arr = [];
10             arr = fs.readdirSync(pathname);
11             arr.forEach((item, index) => {
12                 //递归
13                 removeDir(pathname + '/' + item)
14             })
15             fs.rmdirSync(pathname)
16         } else {
17             //如果是一个文件
18             fs.unlinkSync(pathname)
19         }
20     } else {
21         console.log("文件不存在!")
22     }
23 }
24 
25 //实现拷贝目标目录的所有文件结构
26 function copyDir(fromPath, toPath) {
27     if (fs.existsSync(fromPath)) {
28         if (fs.statSync(fromPath).isDirectory()) {
29             fs.mkdirSync(toPath)
30             let arr = fs.readdirSync(fromPath);
31             arr.forEach((item, index) => {
32                 copyDir(fromPath + '/' + item, toPath + '/' + item)
33             })
34         } else {
35             let content = fs.readFileSync(fromPath);
36             fs.writeFileSync(toPath, content)
37         }
38     } else {
39         console.log("文件不存在!")
40     }
41 }
42 
43 //实现目标目录的扁平化展示
44 function flatDir(fromPath, toPath) {
45     if (fs.existsSync(fromPath)) {
46         if (fs.statSync(fromPath).isDirectory()) {
47             let arr = fs.readdirSync(fromPath);
48             arr.forEach((item, index) => {
49                 list.push(item)
50                 flatDir(fromPath + '/' + item, toPath)
51             })
52         }
53     } else {
54         console.log("文件不存在!")
55     }
56     fs.writeFileSync(toPath, list)
57 }
58 
59 module.exports={
60     removeDir,
61     copyDir,
62     flatDir
63 }
64 
65 // removeDir("./test")
66 // copyDir("./src","./test")
67 flatDir("./src", "./test.txt")

 

本文github地址:https://github.com/Joyceandlee/operationDir

posted @ 2019-09-04 09:44  Joyceandlee  阅读(806)  评论(0编辑  收藏  举报