L.T
L.T

Reputation: 2589

How can get the file directory that require my npm packages

I created a npm package. In the function,I need to know whice file require my package. How can I do ?

sample: this is my package.json

{
  name: "path-judge",
  main: "lib/index.js"
}

exports.doSomething = function(){
  //how can I get the file path that require this package.
  //....
}

if there is a file test.js require path-judge, like this:

var judge = require("path-judge");

judge.doSomething();

in the index.js how can I get the test.js file path?

the test.js isn't the main function, other file require it.

for example: node other.js other.js:

test = require '../../test.js'

//...

console.log('....')

Upvotes: 0

Views: 42

Answers (1)

mscdex
mscdex

Reputation: 106746

You can check module.parent. If that property exists, then it means the module is being loaded via require() and not node mymodule.js directly.

In this object is a filename property. So you can easily use path.dirname() on this value to extract the directory portion to get the path to the script doing the require(). Example:

var path = require('path');
if (module.parent) {
  console.log(path.dirname(module.parent.filename));
}

Upvotes: 1

Related Questions