fs.opendir()方法用於異步打開文件係統中的目錄。它創建一個用於表示目錄的fs.Dir對象。該對象包含各種可用於訪問目錄的方法。
用法:
fs.opendir( path[, options], callback )
參數:此方法接受上述和以下所述的三個參數:
- path:它是一個字符串,緩衝區或URL,表示必須打開的目錄的路徑。
- options:它是一個String或對象,可用於指定將影響輸出的可選參數。它具有兩個可選參數:
- encoding:它是一個字符串,它指定打開目錄時路徑的編碼以及後續的讀取操作。默認值為“ utf8”。
- bufferSize:它是一個數字,指定讀取目錄時在內部緩衝的目錄條目的數量。更高的值意味著更高的性能,但會導致更高的內存使用率。默認值為“ 32”。
- callback:該方法執行時將調用該函數。
- err:如果方法失敗,將引發錯誤。
- dir:這是由表示目錄的方法創建的fs.Dir對象。
以下示例說明了Node.js中的fs.opendir()方法:
範例1:
// Node.js program to demonstrate the
// fs.opendir() method
// Import the filesystem module
const fs = require('fs');
// Open the directory
console.log("Opening the directory");
fs.opendir(
// Path of the directory
"example_dir",
// Options for modifying the operation
{ encoding:"utf8", bufferSize:64 },
// Callback with the error and returned
// directory
(err, dir) => {
if (err) console.log("Error:", err);
else {
// Print the pathname of the directory
console.log("Path of the directory:", dir.path);
// Close the directory
console.log("Closing the directory");
dir.closeSync();
}
}
);
輸出:
Opening the directory Path of the directory:example_dir Closing the directory
範例2:
// Node.js program to demonstrate the
// fs.opendir() method
// Import the filesystem module
const fs = require('fs');
// Function to get current filenames
// in directory
filenames = fs.readdirSync("example_dir");
console.log("\nCurrent filenames in directory:");
filenames.forEach((file) => {
console.log(file);
});
// Open the directory
fs.opendir("example_dir", (err, dir) => {
if (err) console.log("Error:", err);
else {
// Print the pathname of the directory
console.log("\nPath of the directory:", dir.path);
// Read the files in the directory
// as fs.Dirent objects
console.log("First Dirent:", dir.readSync());
console.log("Next Dirent:", dir.readSync());
console.log("Next Dirent:", dir.readSync());
}
});
輸出:
Current filenames in directory: file_a.txt file_b.txt Path of the directory:example_dir First Dirent:Dirent { name:'file_a.txt', [Symbol(type)]:1 } Next Dirent:Dirent { name:'file_b.txt', [Symbol(type)]:1 } Next Dirent:null
參考: https://nodejs.org/api/fs.html#fs_fs_opendir_path_options_callback
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js GM blur()用法及代碼示例
- Node.js GM orderedDither()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
- Node.js GM charcoal()用法及代碼示例
- Node.js GM paint()用法及代碼示例
- Node.js GM flip()用法及代碼示例
- Node.js GM solarize()用法及代碼示例
- Node.js GM motionBlur()用法及代碼示例
- Node.js GM flop()用法及代碼示例
- Node.js GM modulate()用法及代碼示例
- Node.js GM minify()用法及代碼示例
- Node.js GM spread()用法及代碼示例
- Node.js GM magnify()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.opendir() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。