Node.js fs.realpath() Method
Last Updated :
12 Oct, 2021
Improve
The fs.realPath() method is used to compute the canonical pathname of the given path. It does so by resolving the
javascript
Output:
javascript
Output:
.
, ..
and the symbolic links in the path.
Syntax:
fs.realpath( path, options, callback )Parameters: This method accept three 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.
- callback: It is the function that would be called when the method is executed.
- err: It is an error that would be thrown if the operation fails.
- resolvedPath: It is string or buffer that represents the resolved path.
// Node.js program to demonstrate the
// fs.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 + "\\..";
fs.realpath(path1, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("One directory up resolved"
+ " path is: ", resolvedPath);
}
});
// Finding the canonical path
// two directories up
path2 = __dirname + "\\..\\..";
fs.realpath(path2, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("Two directories up 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:\tutorialsExample 2: This example uses fs.realPath() method to demonstrate the different encoding type.
// Node.js program to demonstrate the
// fs.realPath() method
// Import the filesystem module
const fs = require('fs');
path = __dirname + "\\..";
// Getting the canonical path in utf8 encoding
fs.realpath(path, {encoding: "utf8"}, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("The resolved path is:", resolvedPath);
}
});
// Getting the canonical path in hex encoding
fs.realpath(path, {encoding: "hex"}, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("The resolved path is:", resolvedPath);
}
});
// Getting the canonical path in base64 encoding
fs.realpath(path, {encoding: "base64"}, (error, resolvedPath) => {
if (error) {
console.log(error);
}
else {
console.log("The resolved path is:", resolvedPath);
}
});
The resolved path is: G:\tutorials The resolved path is: 473a5c7475746f7269616c73 The resolved path is: RzpcdHV0b3JpYWxzReference: https://nodejs.org/api/fs.html#fs_fs_realpath_path_options_callback