Node-文件操作常用封装

2019-06-17  本文已影响0人  Ricoywang

一、判断类

function fsExistsSync(path) {
    try{
        fs.accessSync(path,fs.F_OK);
    }catch(e){
        return false;
    }
    return true;
}
// 判断制定路径是否是文件
function isFile(dir) {
  return fs.statSync(dir).isFile();
}
// 判断制定路径是否是文件夹
function isFile(dir) {
  return fs.statSync(dir).isDirectory()
}

二、读取类

let  fs = require('fs');
let  join = require('path').join;
/**
 * 
 * @param startPath  起始目录文件夹路径
 * @returns {Array}
 */
function findSync(startPath) {
    let result=[];
    function finder(path) {
        let files=fs.readdirSync(path);
        files.forEach((val,index) => {
            let fPath=join(path,val);
            let stats=fs.statSync(fPath);
            if(stats.isDirectory()) finder(fPath);
            if(stats.isFile()) result.push(fPath);
        });

    }
    finder(startPath);
    return result;
}
let fileNames=findSync('./');
点击上方连接
...
|-- components
    -- index.js
    -- file.js
    -- components-dir-tree.json  // 生成的文件树对象的输出文件,方便查看
    -- no
    -- test
       -- aa
        -- cc

三、创建生成

上一篇下一篇

猜你喜欢

热点阅读