Does anyone know how to get the name of a module in node.js / javascript
so lets say you do
var RandomModule = require ("fs")
.
.
.
console.log (RandomModule.name)
// -> "fs"
Does anyone know how to get the name of a module in node.js / javascript
so lets say you do
var RandomModule = require ("fs")
.
.
.
console.log (RandomModule.name)
// -> "fs"
I don't know why you would need that, but there is a way.
The
module
variable, which is loaded automatically in every node.js file, contains an array calledchildren
. This array contains every children module loaded byrequire
in your current file.This way, you need to strict compare your loaded reference with the cached object version in this array in order to discover which element of the array corresponds to your module.
Look this sample:
This code will find the correspondence in
children
object and bring it's id.I put
module
as a parameter of my function so you can export it to a file. Otherwise it would show you modules of wherediscoverChildModule
function resides (if it is in the same file won't make any diference, but if exported it will).Notes:
../src/routes/headers
. You will find something like:/Users/david/git/...
var Schema = require('mongoose').Schema
. It is possible to make a function which is capable of this, but it will suffer many issues.From within a module (doesn't work at the REPL) you can...
And you'll get '/home/ubuntu/workspace/src/admin.js'
If you are trying to trace your dependencies, you can try using require hooks.
Create a file called
myRequireHook.js
This code will hook every
require
call and log it into your console.Not exactly what you asked first, but maybe it helps you better.
And you need to call just once in your main .js file (the one you start with
node main.js
).So in your
main.js
, you just do that:It will trace
require
in your other modules as well.This is the way transpilers like babel work. They hook every
require
call and transform your code before load.