创建文件夹的例子

  1. const fs = require('fs')
  2. const path = require('path');
  3. try {
  4. // 创建文件夹
  5. fs.mkdirSync('./abc')
  6. } catch (err) {
  7. //
  8. }
  9. const paths = fs.readdirSync('./abc'); // 同步读取当前目录
  10. paths.forEach(item => {
  11. console.log(item)
  12. // eslint-disable-next-line
  13. const __src = path.resolve(__dirname, './abc', item)
  14. console.log(__src)
  15. fs.stat(__src, function(err, stats) {
  16. if (err) {
  17. console.log(err)
  18. }
  19. if (stats.isFile()) { //如果是个文件则拷贝
  20. console.log('文件')
  21. } else {
  22. console.log('文件夹')
  23. }
  24. })
  25. })

删除文件的例子

  1. const fs = require('fs')
  2. const path = require('path');
  3. // eslint-disable-next-line
  4. deleteFolder(path.resolve(__dirname, './abc'));
  5. function deleteFolder (path) {
  6. let files = [];
  7. if (fs.existsSync(path)) {
  8. files = fs.readdirSync(path);
  9. files.forEach(function(file) {
  10. let curPath = path + '/' + file;
  11. if (fs.statSync(curPath).isDirectory()) {
  12. deleteFolder(curPath);
  13. } else {
  14. fs.unlinkSync(curPath);
  15. }
  16. });
  17. fs.rmdirSync(path);
  18. }
  19. }