📜  Node.js fsPromises.realpath() 方法

📅  最后修改于: 2022-05-13 01:56:28.251000             🧑  作者: Mango

Node.js fsPromises.realpath() 方法

fsPromises.realPath()方法使用与fs.realpath.native()函数相同的语义确定路径的实际位置,然后使用解析的路径解析 Promise。仅支持可以转换为UTF8字符串的路径。

句法:

fsPromises.realpath( path, options )

参数:此方法接受上面提到的两个参数,如下所述:

  • path:它保存必须解析的目录的路径。它可以是字符串、缓冲区或 URL。
  • options:它是一个字符串或对象,可用于指定会影响操作的可选参数。它有一个可选参数:
    • encoding:它是一个字符串,它定义了解析路径的编码。

下面的示例说明了 Node.js 中的fs.PromisesrealPath()方法:

示例 1:此示例使用fsPromises.realPath()方法获取给定路径的规范路径。

Node.js
// Node.js program to demonstrate the 
// fsPromises.realPath() method 
    
// Import the filesystem module 
const fs = require('fs'); 
    
console.log("Current Directory Path: ", __dirname); 
    
// Finding the canonical path 
// one directory up 
path1 = __dirname + "\\.."; 
    
fsPromises.realpath(path1, (error, resolvedPath)) 
    console.log("One directory up resolved"
      + " path is: ", resolvedPath); 
     
  
    
// Finding the canonical path 
// two directories up 
path2 = __dirname + "\\..\\.."; 
    
fsPromises.realpath(path2, (resolvedPath)) 
    
    console.log("Two directories up resolved"
          + " path is:", resolvedPath);


Node.js
// Node.js program to demonstrate the 
// fsPromises.realPath() method 
    
// Import the filesystem module 
const fs = require('fs'); 
    
path = __dirname + "\\.."; 
    
// Getting the canonical path in utf8 encoding 
fsPromises.realpath(path, {encoding: "utf8"})
console.log("The resolved path is:", resolvedPath); 
     
// Getting the canonical path in hex encoding 
fsPromises.realpath(path, {encoding: "hex"}) 
console.log("The resolved path is:", resolvedPath); 
    
// Getting the canonical path in base64 encoding 
fsPromises.realpath(path, {encoding: "base64"})
console.log("The resolved path is:", resolvedPath);


输出:

Current Directory Path: G:\tutorials\nodejs-fs-realPath
Two directories up resolved path is: G:\
One directory up resolved path is: G:\tutorials

示例 2:本示例使用fsPromises.realPath()方法来演示不同的编码类型。

节点.js

// Node.js program to demonstrate the 
// fsPromises.realPath() method 
    
// Import the filesystem module 
const fs = require('fs'); 
    
path = __dirname + "\\.."; 
    
// Getting the canonical path in utf8 encoding 
fsPromises.realpath(path, {encoding: "utf8"})
console.log("The resolved path is:", resolvedPath); 
     
// Getting the canonical path in hex encoding 
fsPromises.realpath(path, {encoding: "hex"}) 
console.log("The resolved path is:", resolvedPath); 
    
// Getting the canonical path in base64 encoding 
fsPromises.realpath(path, {encoding: "base64"})
console.log("The resolved path is:", resolvedPath); 

输出:

The resolved path is: G:\tutorials
The resolved path is: 473a5c7475746f7269616c73
The resolved path is: RzpcdHV0b3JpYWxz

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