Node.js fs.readdirSync()方法用法示例

2021年4月12日09:02:30 发表评论 1,167 次浏览

fs.readdirSync()方法用于同步读取给定目录的内容。该方法返回一个数组, 其中包含目录中的所有文件名或对象。 options参数可用于更改从方法返回文件的格式。

语法如下:

fs.readdirSync( path, options )

参数:此方法接受上面提到并在下面描述的两个参数:

  • path:它包含必须从中读取内容的目录路径。它可以是字符串, 缓冲区或URL。
  • options:它是一个对象, 可用于指定将影响方法的可选参数。它具有两个可选参数:
    • 编码:它是一个字符串值, 该字符串值指定给回调参数指定的文件名使用哪种编码。默认值为" utf8"。
    • withFileTypes:它是一个布尔值, 它指定是否将文件作为fs.Dirent对象返回。默认值为" false"。

返回值:它返回包含目录中文件的String, Buffer或fs.Dirent对象的数组。

以下示例说明了fs.readdirSync()方法在Node.js中:

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

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

输出如下:

Current directory filenames:
CONTRUBUTIONS.txt
index.html
index.js
package.json
README.md

Current directory files:
Dirent { name: 'CONTRUBUTIONS.txt', [Symbol(type)]: 1 }
Dirent { name: 'index.html', [Symbol(type)]: 1 }
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'README.md', [Symbol(type)]: 1 }

示例2:本示例使用fs.readdirSync()方法仅返回扩展名为" .md"的文件名。

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

输出如下:

Filenames with the .md extension:
README.md

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


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: