How to find the path of a file using fs.realPath()

Hello and welcome to my blog!!!

Below is a guide on using the fs modules realPath() method found in nodejs.

Few things to know about….

The fs.realPath() will return the canonical path which basically is the absolute path. The difference is the canonical path is the most accurate representation of the path.

For example an absolute path would be:
“C:\USER\COREY\DESKTOP\TEST.TXT”
“C:\user\corey\desktop\test.txt”

The canonical path would be the most accurate representation:
“C:\Users\Corey\Desktop\test.txt”

You will notice that the absolute path can be case insensitive and the canonical path is case sensitive to how the items are named on the system.

The fs.realpath() has 3 parameters the path, options (which is an optional parameter), and a callpack of two arguments (err, resolvedPath).

The signature for  fs.realpath()  is:

fs.realpath(path[, options], callback)

You probably can just ignore the 2nd parameter “options.” From my experimenting it can do 2 things pass a object which could be useful if you want to make changes to an object inside the function. Secondly, it can change the encoding of the output. The default is UTF8 which should be fine in most cases.

Here is a list of other encoding’s I found.

'utf8'
'ucs2'
'utf8'
'ucs2'
'utf-8'
'ascii'
'ucs-2'
'utf-8'
'ascii'
'ucs-2'
'utf16le' 
'utf-16le'
'latin1'
'binary'
'base64'
'hex' 

 

Lets Take a Look at an small program to demonstrate fs.realpath().

This program will look for a file called test.txt located in the above directory and return the canonical path.

Note:
The fs.realpath() will run asynchronously so you will need to put it inside a promise to get the correct results.

const fs = require('fs');
let relativePath = '../test.txt';

let testRealPath = new Promise((resolve, reject) => {
    fs.realpath(relativePath, (err, resolvedPath) => {
        if (err) {
            reject(err);
        } else {
            resolve(resolvedPath);
        }
    });
});

testRealPath.then((canonicalPath) => {
    console.log("My Canonical path for " + relativePath + " is: " + canonicalPath);
}).catch((err) => {
    console.log(err);
});

Output: My Canonical path for ../test.txt is: C:\Users\Corey\Desktop\test.txt

 

Leave a Reply

Your email address will not be published. Required fields are marked *