Node.js: How to check if folder is empty or not with out uploading list of files

后端 未结 6 1979
日久生厌
日久生厌 2021-02-12 18:59

I am using Node.js.

I want to check if folder is empty or not? One option is to use fs.readdir but it loads whole bunch of

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 19:49

    Duplicate from my answer in how to determine whether the directory is empty directory with nodejs

    There is the possibility of using the opendir method call that creates an iterator for the directory.

    This will remove the need to read all the files and avoid the potential memory & time overhead

        import {promises as fsp} from "fs"
        const dirIter = await fsp.opendir(_folderPath);
        const {value,done} = await dirIter[Symbol.asyncIterator]().next();
        await dirIter.close()
    

    The done value would tell you if the directory is empty

提交回复
热议问题