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?
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