Suppose we have a terminal executing the node.js file and the terminal is open at
/home/user
And the path of node.js file is
/home/user/test
Then we can get the relative path to a file in two different ways
var path = require("path");
let path1=path.join('__dirname','../relative/path/file.txt');
fs.readFile(path1);
let path2=path.join('./','../relative/path/file.txt');
fs.readFile(path1);
Here '__dirname' represents the actual path where the current node.js file being executed is present i.e.
/home/user/test
and './' represents the path from where the node.js file is being executed i.e.
/home/user
Path where the terminal is currently at and executing the given node.js file
Hence
path1 will represent path relative to the directory that contains the node.js file
path1='/home/user/test/../relative/path/file.txt'
= '/home/user/test/relative/path/file.txt'
path2 will represent the path realtive to the place from where terminal is being run
path2='/home/user/../relative/path/file.txt'
='/home/relative/path/file.txt'
Difference between __dirname and ./ in Node.js
Path Node.js Documentation
__dirname + "/relativ/path"or something likeconst path = require('path'); path.resolve(../relative/path/file.txt")to get the absolute path