美文网首页
Node清空文件夹,文件,自动创建文件夹

Node清空文件夹,文件,自动创建文件夹

作者: i_木木木木木 | 来源:发表于2021-12-17 16:50 被阅读0次
    const fs = require('fs');
    const path = require("path")
    
    /**
     * 删除文件夹下所有文件及将文件夹下所有文件清空-同步方法
     * @param {*} path
     */
    function emptyDir(path) {
        const files = fs.readdirSync(path);
        files.forEach(file => {
            const filePath = `${path}/${file}`;
            const stats = fs.statSync(filePath);
            if (stats.isDirectory()) {
                emptyDir(filePath);
            } else {
                fs.unlinkSync(filePath);
                console.log(`删除${file}文件成功`);
            }
        });
    }
    
    /**
     * 删除指定路径下的所有空文件夹-同步方法
     * @param {*} path
     */
    function rmEmptyDir(path, level=0) {
        const files = fs.readdirSync(path);
        if (files.length > 0) {
            let tempFile = 0;
            files.forEach(file => {
                tempFile++;
                rmEmptyDir(`${path}/${file}`, 1);
            });
            if (tempFile === files.length && level !== 0) {
                fs.rmdirSync(path);
            }
        }
        else {
            level !==0 && fs.rmdirSync(path);
        }
    }
    
    /**
     * 清空指定路径下的所有文件及文件夹-同步方法
     * @param {*} path
     */
    function clearDir(path) {
        emptyDir(path);
        rmEmptyDir(path);
    }
    
    /**
     * 递归创建目录 同步方法
     * @param {*} dirname
     */
    const mkdirsSync = (dirname) => {
        if (fs.existsSync(dirname)) {
            return true;
        } else {
            if (mkdirsSync(path.dirname(dirname))) {
                fs.mkdirSync(dirname);
                return true;
            }
        }
    }
    
    module.exports = {
        rmEmptyDir,
        emptyDir,
        clearDir,
        mkdirsSync
    }
    
    

    相关文章

      网友评论

          本文标题:Node清空文件夹,文件,自动创建文件夹

          本文链接:https://www.haomeiwen.com/subject/lgvifrtx.html