fsPromises.readdir(path[, options])


  • path <string> | <Buffer> | <URL>
  • options <string> | <Object>
    • encoding <string> 默认值: 'utf8'
    • withFileTypes <boolean> 默认值: false
    • recursive <boolean> 如果为 true,将递归读取目录的内容。在递归模式下,它会列出所有文件、子文件和目录。默认值: false
  • 返回:<Promise>,以数组形式返回目录中除 '.''..' 之外的文件名。

读取目录的内容。

【Reads the contents of a directory.】

可选的 options 参数可以是指定编码的字符串,或者是包含 encoding 属性的对象,用于指定文件名的字符编码。如果 encoding 设置为 'buffer',返回的文件名将作为 <Buffer> 对象传递。

【The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames. If the encoding is set to 'buffer', the filenames returned will be passed as <Buffer> objects.】

如果 options.withFileTypes 设置为 true,返回的数组将包含 <fs.Dirent> 对象。

【If options.withFileTypes is set to true, the returned array will contain <fs.Dirent> objects.】

import { readdir } from 'node:fs/promises';

try {
  const files = await readdir(path);
  for (const file of files)
    console.log(file);
} catch (err) {
  console.error(err);
}