2

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
  • You could use __dirname + "/relativ/path" or something like const path = require('path'); path.resolve(../relative/path/file.txt") to get the absolute path Commented Jul 10, 2020 at 16:01

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

What if my app.js is a npm package, and user can import myFunction to there code and call the function with passing a relative path of there file. I need to get the file and process it. How to get the file in that case ? Thanks
In that case you can use let actual_path=path.reslove('__dirname') In Index.js file that will give you actual path of index.js file and can pass it as another argument to myfunction
Is there any non node solution? client side in the browser solution?
No quotes needed around __dirname

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.