How do you get a list of the names of all files present in a directory in Node.js?

后端 未结 25 1231
天涯浪人
天涯浪人 2020-11-22 07:47

I\'m trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

25条回答
  •  清酒与你
    2020-11-22 08:16

    As of Node v10.10.0, it is possible to use the new withFileTypes option for fs.readdir and fs.readdirSync in combination with the dirent.isDirectory() function to filter for filenames in a directory. That looks like this:

    fs.readdirSync('./dirpath', {withFileTypes: true})
    .filter(item => !item.isDirectory())
    .map(item => item.name)
    

    The returned array is in the form:

    ['file1.txt', 'file2.txt', 'file3.txt']
    

    Docs for the fs.Dirent class

提交回复
热议问题