fs.opendirSync()方法用於同步打開文件係統中的目錄。它返回一個fs.Dir對象,該對象用於表示目錄。該對象包含各種可用於訪問目錄的方法。
用法:
fs.opendirSync( path[, options] )
參數:該方法接受上述和以下所述的兩個參數:
- path:它是一個字符串,緩衝區或URL,表示必須打開的目錄的路徑。
- options:它是一個字符串或對象,可用於指定將影響輸出的可選參數。它具有兩個可選參數:
- encoding:它是一個字符串,它指定打開目錄時路徑的編碼以及後續的讀取操作。默認值為“ utf8”。
- bufferSize:它是一個數字,指定讀取目錄時在內部緩衝的目錄條目的數量。更高的值意味著更高的性能,但會導致更高的內存使用率。默認值為“ 32”。
返回值:它返回一個fs.Dir對象,該對象表示目錄,並包含可用於訪問目錄的各種方法。
以下示例說明了Node.js中的fs.opendirSync()方法:
範例1:
// Node.js program to demonstrate the
// fs.opendirSync() method
// Import the filesystem module
const fs = require('fs');
// Open the directory
console.log("Opening the directory");
let openedDir = fs.opendirSync("example_dir");
// Print the pathname of the directory
console.log("\nPath of the directory:", openedDir.path);
// Close the directory
console.log("\nClosing the directory");
openedDir.closeSync();
輸出:
Opening the directory Path of the directory:example_dir Closing the directory
範例2:
// Node.js program to demonstrate the
// fs.opendirSync() 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
openedDir = fs.opendirSync("example_dir");
// Print the pathname of the directory
console.log("\nPath of the directory:", openedDir.path);
// Read the files in the directory
// as fs.Dirent objects
console.log("First Dirent:", openedDir.readSync());
console.log("Next Dirent:", openedDir.readSync());
console.log("Next Dirent:", openedDir.readSync());
輸出:
Current filenames in directory: example1.txt example2.txt Path of the directory:example_dir First Dirent:Dirent { name:'example1.txt', [Symbol(type)]:1 } Next Dirent:Dirent { name:'example2.txt', [Symbol(type)]:1 } Next Dirent:null
參考: https://nodejs.org/api/fs.html#fs_fs_opendirsync_path_options
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js GM thumbnail()用法及代碼示例
- Node.js GM threshold()用法及代碼示例
- Node.js GM segment()用法及代碼示例
- Node.js GM resize()用法及代碼示例
- Node.js GM raise()用法及代碼示例
- Node.js GM quality()用法及代碼示例
- Node.js GM transparent()用法及代碼示例
- Node.js GM roll()用法及代碼示例
- Node.js GM solarize()用法及代碼示例
- Node.js GM spread()用法及代碼示例
- Node.js GM motionBlur()用法及代碼示例
- Node.js GM operator()用法及代碼示例
- Node.js GM shave()用法及代碼示例
- Node.js GM scale()用法及代碼示例
注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.opendirSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。