How to get the file using relative path (argument) in NodeJS

Viewed 2057

I want to get the files using myFunction()

how to get the file if user pass a relative path as function argument

../somewhere/index.js

import {myFunction} from "../pathTo/app.js";
    
myFunction("../relative/path/file.txt");

app.js

export const myFunction = (path) => {
   fs.readFile(path); //=> How to get the file here
};
1 Answers

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

Related