📜  Node.js fs.realpathSync() 方法

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

Node.js fs.realpathSync() 方法

fs.realpathSync() 方法用于同步计算给定路径的规范路径名。它通过解析路径中的 .、.. 和符号链接并返回解析的路径来实现。
句法:

fs.realpathSync( path, options )

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

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

返回:它返回一个表示解析路径的字符串或缓冲区。
下面的示例说明了 Node.js 中的fs.realpathSync() 方法
示例 1:

javascript
// 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);


javascript
// 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);


输出:

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

示例 2:

javascript

// 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