Getting name of a module in node.js

12,148

Solution 1

If you are trying to trace your dependencies, you can try using require hooks.

Create a file called myRequireHook.js

var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function(path) {
    console.log('*** Importing lib ' + path + ' from module ' + this.filename);
    return originalRequire(path);
};

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:

require('./myRequireHook');
var fs = require('fs');
var myOtherModule = require('./myOtherModule');

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.

Solution 2

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 called children. This array contains every child module loaded by require 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:

var pieces = require('../src/routes/headers');

var childModuleId = discoverChildModuleId(pieces, module);
console.log(childModuleId);

function discoverChildModuleId(object, moduleObj) {
    "use strict";
    var childModule = moduleObj.children.find(function(child) {
        return object === child.exports;
    });
    return childModule && childModule.id;
}

This code will find the correspondence in children object and bring its 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 where discoverChildModule function resides (if it is in the same file won't make any difference, but if exported it will).

Notes:

  • Module ids have the full path name. So don't expect finding ../src/routes/headers. You will find something like: /Users/david/git/...
  • My algorithm won't detect exported attributes like var Schema = require('mongoose').Schema. It is possible to make a function which is capable of this, but it will suffer many issues.
Share:
12,148
sourcevault
Author by

sourcevault

Updated on June 18, 2022

Comments

  • sourcevault
    sourcevault almost 2 years

    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"