0

What I am trying to do is creating function like NodeJS require. You can do require("./your-file") and require understand that the file ./your-file is sibling of the calling module, without specifying the full path of the file.

My current problem is getting the directory of current executing function (__dirname of the executing function)

I tried things below:

  • Using module.parent.fileName failed when the calling method wrapped with other function.
  • By reading from V8 stack trace almost there but failed when run inside test runner (Jest)

It should be an easy solution for this, maybe I'm over complicate it?

ktutnik
  • 6,882
  • 1
  • 29
  • 34
  • Actually this is quite complicated, see https://github.com/nodejs/node-v0.x-archive/blob/069dd07a1732c6a752773aaed9e8c18ab472375f/lib/module.js#L354 (determines the context of the `require` function which is the module – Jonas Wilms Jul 18 '18 at 21:14

2 Answers2

0

May be you should use:

var path = require('path'); 
//_dirname will give you the current position

using path package you can achieve this. find Documentation here

Dhaval Chaudhary
  • 5,428
  • 2
  • 24
  • 39
  • Maybe you don't understand my question, how do i got the directory of the current executing module using `path` module? – ktutnik Jul 19 '18 at 22:01
  • yeh i misunderstood. may be this will help https://stackoverflow.com/questions/13227489/how-can-one-get-the-file-path-of-the-caller-function-in-node-js – Dhaval Chaudhary Jul 20 '18 at 06:44
0

Both module.parent.fileName and V8 stack trace works fine, but it will failed if you export the module in the index.js

example:

//src/my-lib.js

function myFunction(){
   const path = module.parent.fileName
   //do stuff
}

then you export the function above in the index.js

//src/index.js
const lib = require("./my-lib")

exports.myFunction = lib.myFunction

in the client code if you import myFunction from index.js the path detected will always /src/index.js

ktutnik
  • 6,882
  • 1
  • 29
  • 34