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


Node.js fs.Dir.path()用法及代碼示例


fs.Dir.path()方法是文件係統模塊中的類fs.Dir的內置應用程序編程接口,用於獲取目錄路徑。

用法:

const dir.path

參數:此方法不接受任何參數。

返回值:此方法返回目錄的路徑。

下麵的程序演示了fs.Dir.path()方法的使用。



範例1: 文件名:index.js

// Node.js program to demonstrate the  
// dir.path() method 
const fs = require('fs'); 
  
// Initiating asyn function 
async function stop(path) { 
  
    // Creating and initiating directory's 
    // underlying resource handle 
    const dir = await fs.promises.opendir(path); 
  
    console.log("All the dirent before operation:- "); 
  
    for (var i = 0; i <= 2; i++) { 
        console.log(((dir.readSync())).name); 
    } 
  
    // Getting the path of the directory 
    // by using path() method 
    const pathval = dir.path; 
  
    console.log("All the dirent after operation:- "); 
  
    for (var i = 0; i <= 2; i++) { 
        console.log(((dir.readSync())).name); 
    } 
  
    // Display the result 
    console.log("\nPath:- " + pathval); 
} 
  
// Catching error 
stop('./').catch(console.error);

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

node index.js

輸出:

All the dirent before operation:- 
books.txt
datastore.json
example.txt
All the dirent after operation:-
index.js
node_modules
package-lock.json

Path:- ./

範例2: 文件名:index.js

// Node.js program to demonstrate the  
// dir.path() method 
const fs = require('fs'); 
const fsPromises = fs.promises; 
  
// Name of the directory to be created 
let directo = './temp'; 
  
// Checking if the directory is 
// present or not 
if (!fs.existsSync(directo)) { 
    fs.mkdirSync(directo); 
} 
  
// Initiating asyncrionise function 
async function funct(path) { 
  
    // Initializng dir 
    let dir = null; 
    let pathval = null; 
  
    try { 
  
        // Creating and initiating directory's 
        // underlying resource handle 
        dir = await fs.promises.opendir('./'); 
  
  
        console.log("All the dirent before operation:- " + 
            ((dir.readSync()))); 
  
        // Getting the path of the directory 
        // by using path() method 
        pathval = dir.path; 
  
    } finally { 
  
        if (dir) { 
  
            // Close the file if it is opened. 
            console.log("Path:- " + pathval); 
  
            console.log("All the dirent after operation:- " + 
                ((dir.readSync()))); 
            await dir.close(); 
        } 
    } 
} 
  
funct('./').catch(console.error);

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

node index.js

輸出:

All the dirent before operation:- [object Object]
Path:- ./
All the dirent after operation:- [object Object]

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




相關用法


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