fs.readdir ignore directories

后端 未结 2 1060
温柔的废话
温柔的废话 2021-02-08 00:20

I would like to scan the folder, but ignore all the folders/directories that are included in it. All I have in the (C:/folder/) are .txt files and other folders, I just want to

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 00:28

    Use fs.readdir or fs.readdirSync method with options { withFileTypes: true } and then do filtration using dirent.isFile (requires Node 10.10+).

    Sync version

    const fs = require('fs');
    const dirents = fs.readdirSync(DIRECTORY_PATH, { withFileTypes: true });
    const filesNames = dirents
        .filter(dirent => dirent.isFile())
        .map(dirent => dirent.name);
    // use filesNames
    

    Async version (with async/await, requires Node 11+)

    import { promises as fs } from 'fs';
    
    async function listFiles(directory) {
        const dirents = await fs.readdir(directory, { withFileTypes: true });
        return dirents
            .filter(dirent => dirent.isFile())
            .map(dirent => dirent.name);
    }
    

    Async version (with callbacks)

    const fs = require('fs');
    fs.readdir(DIRECTORY_PATH, { withFileTypes: true }, (err, dirents) => {
        const filesNames = dirents
            .filter(dirent => dirent.isFile())
            .map(dirent => dirent.name);
        // use filesNames
    });
    

提交回复
热议问题