Skip to content
Related Articles
Open in App
Not now

Related Articles

Node.js fs.realpathSync() Method

Improve Article
Save Article
  • Last Updated : 11 Oct, 2021
Improve Article
Save Article

The fs.realpathSync() method is used to synchronously compute the canonical pathname of a given path. It does so by resolving the ., .. and the symbolic links in the path and returning the resolved path.
Syntax: 

fs.realpathSync( path, options )

Parameters: This method accept two parameters as mentioned above and described below:  

  • path: It holds the path of the directory that has to be resolved. It can be a String, Buffer or URL.
  • options: It is an string or object that can be used to specify optional parameters that will affect the operation. It has one optional parameter:
    • encoding: It is a string which defines the encoding of the resolved path.

Returns: It returns a String or a Buffer that represents the resolved path.
Below examples illustrate the fs.realpathSync() method in Node.js:
Example 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);


Output:

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

Example 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);


Output:

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

Reference: https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!