如何使用 Nodejs 递归收集目录和文件

Es6版本

//从根目录递归收集文件和目录信息
const fs = require('fs');
const path = require('path');

let collectObj = {
    filesList: [],
    dirsList: []
};

function readFileList(dir, collectObj) {
    let {
        filesList,
        dirsList,
    } = collectObj
    const files = fs.readdirSync(dir);
    files.forEach((item, index) => {
        var fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            dirsList.push(fullPath);
            readFileList(path.join(dir, item), collectObj); //递归读取文件
        } else {

            filesList.push(fullPath);
        }
    });
    return collectObj;

}
collectObj = readFileList(__dirname, collectObj)

console.log(collectObj)

Typescript版本

//从根目录递归收集文件和目录信息
const fs = require('fs');
const path = require('path');
interface CollectObjType {
    filesList: Array  ,
    dirsList: Array  ,
}
let collectObj: CollectObjType = {
    filesList: [],
    dirsList: []
};

function readFileList(dir, collectObj): CollectObjType {
    let {
        filesList,
        dirsList,
    } = collectObj
    const files:Array = fs.readdirSync(dir);
    files.forEach((item, index) => {
        var fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            dirsList.push(fullPath);
            readFileList(path.join(dir, item), collectObj); //递归读取文件
        } else {

            filesList.push(fullPath);
        }
    });
    return collectObj;

}
collectObj = readFileList(__dirname, collectObj)

console.log(collectObj)

你可能感兴趣的:(软件研发,nodejs,python,os)