1. Clear a folder

  • The incoming path
  • Read the middle file of a folder
  • Read files and folders

2. Modules used

path

  • __dirName Directory name of the current module
  • The path module
const path = require('path');
// The method to parse the path
const dir = path.resolve(__dirname, 'File name')
Copy the code

fs

const fs = require('fs');
fs.existsSync(dir); // Verify that the directory exists
fs.readdirSync(dir); // Read files in directory (including files + folders)
    
Are these files files or folders?
const stat = fs.lstatSync(path); // Return the current path information fs.stats
stat.isDirectory(); // True is returned if the fs.Dirent object describes the file system directory.
stat.isFile(); // Return true if the fs.Dirent object describes a regular file.
Copy the code

3. Clear a directory

const fs = require('fs');
const path = require('path');
const removeDir = (option) = > {
    const { dir } = option;
    if(! dir || ! fs.existsSync(dir))return;

    // Read the folder in the directory
    const files = fs.readdirSync(dir);
    files.forEach((file) = > {
        const filePath = path.resolve(dir, file);
        const stat = fs.lstatSync(filePath);
        // If it is directory, recurse
        if (stat.isDirectory()) {
            removeDir({ dir: filePath });
            return;
        }
        // Delete it if it is a file
        if(stat.isFile()) { fs.unlinkSync(filePath); }});// Delete an empty directory
    fs.rmdirSync(dir);
};

removeDir({dir:path.resovle(__dirname,'.cache')});
Copy the code

4. Of course, this is not the final solution

Project we see the most is the package below www.npmjs.com/package/rim…

npm install rimraf
Copy the code

5. But

  • Node’s API will have to be looked at sometime, because the front end can finally do something other than the front end
  • Node finally makes it possible for the front end to touch the back end of the technology stack, ha ha ~~~~