-1

Node, as you all know has a require function. When you call this function with a relative path. The relative path is based on the location of your call. How is this done?

I want to make a function that reads a file, which also has the same behavior. That when I pass it a relative path, the path is determined based on the location of the call.

So, basically what I'm looking for is for a call as readFile("./my_file.txt") to be interpreted as readFile(__dirname + "/my_file.txt").

I could of-course just always add __dirname, but I'm trying to eliminate that, and I'm curious how require does it.

Matthijn
  • 3,126
  • 9
  • 46
  • 69
  • doing `require('./path')` is the same that `require(__dirname + '/path')` – Yerko Palma Mar 09 '17 at 20:56
  • I know. But with require I don't have to write `__dirname`, I'm trying to find out if it is possible to make a function of my own that also does not require adding `__dirname` every time. Perhaps my question was not clear. – Matthijn Mar 09 '17 at 20:57

3 Answers3

0

I define the following method in my main app.js:

global.rootRequire = function(name) {
    return require(__dirname + '/' + name);
}

Then in the various other files I can use:

const data = rootRequire('services/data');
MattB
  • 1,104
  • 8
  • 15
0

You should use process.cwd() method, as it does exactly what you want. A function like what @MattB suggest, but replacing __dirname

function relativeRequire (name) {
    return require(process.cwd() + '/' + name);
}    

const data = rootRequire('services/data');
Yerko Palma
  • 12,041
  • 5
  • 33
  • 57
  • Ins't process.cwd() the path of where the original script was executed from? Which doesn't have to be the file I'm currently in. – Matthijn Mar 10 '17 at 09:18
  • Yeah, I though that whats what you wanted. I guess you should explain a bit your problem... – Yerko Palma Mar 10 '17 at 11:47
  • If I pass a relative path into the require function, it is seen relative from the file that makes the call to require. I basically want that for my own function. So if I call my "readFile" with a relative path, it should be relative from the file where I make the call. Without having to add __dirname to the call. – Matthijn Mar 10 '17 at 13:09
0

Seems the answer in Wrap require in Node.js which can resolve relative path call is one that works. Getting a stack trace in the function that is called and then determine where the callers file resides.

Not too fond of that solution and probably won't use it. But it's one that works. Feel free to suggest better ways.

Community
  • 1
  • 1
Matthijn
  • 3,126
  • 9
  • 46
  • 69