當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js fs.dirent.name用法及代碼示例

fs.Dirent.name屬性是文件係統模塊內的類fs.Dirent的內置應用程序編程接口,用於提供特定Dirent的名稱。

用法:

const dirent.name

參數:此屬性不接受任何參數。

返回值:此屬性返回特定Dirent的名稱。

以下示例程序旨在說明Node.js中fs.dirent.name屬性的使用:



範例1: 文件名:index.js

// Node.js program to demonstrate the  
// dirent.name property 
const fs = require('fs'); 
  
// Initiating asyn function 
async function stop(path) { 
  
    // Creating and initiating dir's  
    // underlying resource handle 
    const dir = await  
        fs.promises.opendir(path); 
  
    // Synchronously reading the dir's 
    // underlying resource handle 
    // using readSync() mehtod 
    for (var i = 0; i <= 6; i++) { 
  
        // Checking if the particular 
        // dirent is SymbolicLink or  
        // not by using name() method 
        const value = (dir.readSync()).name; 
  
        // Display the result 
        console.log(value); 
    } 
} 
  
// Catching error 
stop('./').catch(console.error);

使用以下命令運行index.js文件:

node index.js

輸出:

abcd.cer
cert.cer
certfile.cer
certificate1.cer
example.txt
features
filename.txt

範例2: 文件名:index.js

// Node.js program to demonstrate the  
// dirent.name property 
const fs = require('fs'); 
  
// Initiating asyn function 
async function stop(path) { 
  
    let dir = null; 
  
    try { 
  
        // Creating and initiating directory's 
        // underlying resource handle 
        dir = await fs.promises.opendir( 
            new URL('file:///F:/java/')); 
  
        // Synchronously reading the File's 
        // underlying resource handle 
        // using readSync() method 
        for (var i = 0; i <= 3; i++) { 
  
            // Checking if the particular dirent  
            // is File or not by using isFile() method 
            const value = (dir.readSync()).name; 
  
            // Display the result 
            console.log(dir.readSync()); 
            console.log(value); 
        } 
    } finally { 
  
        if (dir) { 
  
            // Display the result 
            console.log("dir is closed successfully"); 
  
            // Synchronously closeSyncing the  
            // directory's underlying resource handle 
            const promise = dir.closeSync(); 
        } 
    } 
} 
  
// Catching error 
stop('./').catch(console.error);

使用以下命令運行index.js文件:

node index.js

輸出:

Dirent { name:'books.txt', [Symbol(type)]:1 }
abcd.cer
Dirent { name:'certfile.cer', [Symbol(type)]:1 }
cert.cer
Dirent { name:'example.com_index.html', [Symbol(type)]:1 }
certificate1.cer
Dirent { name:'features', [Symbol(type)]:2 }
example.txt

參考: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dirent_name




相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node.js fs.dirent.name Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。