当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js fs.realpathSync()用法及代码示例


fs.realpathSync()方法用于同步计算给定路径的规范路径名。它通过解决...以及路径中的符号链接并返回已解析的路径。

用法:

fs.realpathSync( path, options )

参数:此方法接受上述和以下所述的两个参数:



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

返回值:它返回一个代表解析路径的字符串或缓冲区。

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

范例1:

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

输出:

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

范例2:

// Node.js program to demonstrate the 
// fs.realpathSync() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
path = __dirname + "\\.."; 
  
// Getting the canonical path is utf8 encoding 
resolvedPath = fs.realpathSync(path, { encoding:"utf8" }); 
console.log("The resolved path is:", resolvedPath); 
  
// Getting the canonical path is hex encoding 
resolvedPath = fs.realpathSync(path, { encoding:"hex" }); 
console.log("The resolved path is:", resolvedPath); 
  
// Getting the canonical path is base64 encoding 
resolvedPath = fs.realpathSync(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_fs_realpathsync_path_options




相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | fs.realpathSync() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。