📜  Node.js fs.readdir() 方法

📅  最后修改于: 2022-05-13 01:56:23.351000             🧑  作者: Mango

Node.js fs.readdir() 方法

fs.readdir() 方法用于异步读取给定目录的内容。此方法的回调返回目录中所有文件名的数组。 options 参数可用于更改从方法返回文件的格式。

句法:

fs.readdir( path, options, callback )

参数:此方法接受三个参数,如上所述,如下所述:

  • path:它保存必须从中读取内容的目录的路径。它可以是字符串、缓冲区或 URL。
  • options:它是一个对象,可用于指定将影响方法的可选参数。它有两个可选参数:
    • encoding:它是一个字符串值,它指定将哪种编码用于给回调参数的文件名。默认值为“utf8”。
    • withFileTypes:它是一个布尔值,指定文件是否将作为 fs.Dirent 对象返回。默认值为“假”。
  • callback:方法执行时调用的函数。
    • err:如果操作失败将抛出的错误。
    • files:它是包含目录中文件的 String、Buffer 或 fs.Dirent 对象的数组。

下面的示例说明了 Node.js 中的fs.readdir() 方法

示例 1:本示例使用 fs.readdir() 方法返回目录中的文件名或文件对象。

// Node.js program to demonstrate the
// fs.readdir() method
  
// Import the filesystem module
const fs = require('fs');
  
// Function to get current filenames
// in directory
fs.readdir(__dirname, (err, files) => {
  if (err)
    console.log(err);
  else {
    console.log("\nCurrent directory filenames:");
    files.forEach(file => {
      console.log(file);
    })
  }
})
  
// Function to get current filenames
// in directory with "withFileTypes"
// set to "true" 
  
fs.readdir(__dirname, 
  { withFileTypes: true },
  (err, files) => {
  console.log("\nCurrent directory files:");
  if (err)
    console.log(err);
  else {
    files.forEach(file => {
      console.log(file);
    })
  }
})

输出:

Current directory filenames:
index.js
package.json
text_file_a.txt
text_file_b.txt

Current directory files:
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'text_file_a.txt', [Symbol(type)]: 1 }
Dirent { name: 'text_file_b.txt', [Symbol(type)]: 1 }

示例 2:此示例使用 fs.readdir() 方法仅返回带有“.txt”扩展名的文件名。

// Node.js program to demonstrate the
// fs.readdir() method
  
// Import the filesystem module
const fs = require('fs');
const path = require('path');
  
// Function to get current filenames
// in directory with specific extension
fs.readdir(__dirname, (err, files) => {
  if (err)
    console.log(err);
  else {
    console.log("\Filenames with the .txt extension:");
    files.forEach(file => {
      if (path.extname(file) == ".txt")
        console.log(file);
    })
  }
})

输出:

Filenames with the .txt extension:
text_file_a.txt
text_file_b.txt

参考: https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback