当前位置 : 主页 > 网络编程 > JavaScript >

Node FS Operation

来源:互联网 收集:自由互联 发布时间:2021-06-30
Get Type Files // Created by Joe on 2017/9/22.const fs = require('fs');const path = require('path');const getTypeFiles = (filePath, type = [], recursive = true) = { let fileList = [], curPath = filePath; if (type.length === 0) return fileLi
Get Type Files
// Created by Joe on 2017/9/22.

const fs = require('fs');
const path = require('path');

const getTypeFiles = (filePath, type = [], recursive = true) => {
    let fileList = [], curPath = filePath;
    if (type.length === 0) return fileList;
    let stat = fs.statSync(curPath);
    if (stat.isDirectory()) {
        let dirs = fs.readdirSync(curPath);
        for (let dir of dirs) {
            curPath = path.join(filePath, dir);
            stat = fs.statSync(curPath);
            if (stat.isFile()) {
                if (type.indexOf(path.extname(curPath)) !== -1)
                    fileList.push(path.basename(curPath));
            } else if (recursive) {
                fileList.push(...getTypeFiles(curPath, type));
            }
        }
    } else {
        if (type.indexOf(path.extname(curPath)) !== -1) {
            fileList.push(path.basename(curPath));
        }
    }
    return fileList;
};

// module.exports = getTypeFiles;
Create Directory
// create dir async
const mdAsync = (dir) => {
    fs.exists(dir, (exists) => {
        if (!exists) {
            mdAsync(path.dirname(dir), () => {
                fs.mkdir(dir);
            });
        }
    });
};

// create dir sync
const mdSync = (dir) => {
    if (fs.existsSync(dir)) return true;
    if (mdSync(path.dirname(dir))) {
        fs.mkdirSync(dir);
        return true;
    }
};
网友评论