davidhq
davidhq

Reputation: 4760

How to know the exact path to file that was required()

In node console I do: require('path') or require('assert') => how to find out exactly which file was loaded by the command (the absolute path to the file)

I couldn't find a decisive answer anywhere and I couln't get to it myself... I thought it would be easier than it seems to be...

Upvotes: 2

Views: 385

Answers (1)

Tyler
Tyler

Reputation: 18177

I don't think this is as simple as you were hoping but using the require object you can do this:

// Load up some modules
var _ = require('lodash');
var natural = require('natural');

// These are where Node will go looking for the modules above
console.log('Paths:');
console.log(require.main.paths);

// You can print out the id of each module, which is the path to its location
console.log('Module IDs:');
require.main.children.forEach((module) => {
    console.log(module.id);
});

Output:

$ node index.js

Paths:
[ '/Users/tyler/Desktop/js_test/node_modules',
  '/Users/tyler/Desktop/node_modules',
  '/Users/tyler/node_modules',
  '/Users/node_modules',
  '/node_modules' ]

Module IDs:
/Users/tyler/Desktop/js_test/node_modules/lodash/lodash.js
/Users/tyler/Desktop/js_test/node_modules/natural/lib/natural/index.js

As far as I can tell the module IDs will be in the order that you require them, so you should be able to work with their indexes or search through the module ids dynamically for whatever you are looking for.

Upvotes: 1

Related Questions