Node.js fsPromises.realpath() Method
Last Updated :
08 Oct, 2021
Improve
The fsPromises.realPath() method determines the actual location of path using the same semantics as the fs.realpath.native() function then resolves the Promise with the resolved path. Only paths that can be converted to UTF8 strings are supported.
Syntax:
fsPromises.realpath( path, options )
Parameters: This method accepts 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 a 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.
Below examples illustrate the fs.PromisesrealPath() method in Node.js:
Example 1: This example uses fsPromises.realPath() method to get the canonical paths of the given path.
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); |
Output:
Current Directory Path: G:\tutorials\nodejs-fs-realPath Two directories up resolved path is: G:\ One directory up resolved path is: G:\tutorials
Example 2: This example uses fsPromises.realPath() method to demonstrate the different encoding type.
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); |
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_fspromises_realpath_path_options