Getting name of a module in node.js

importvault picture importvault · Nov 27, 2015 · Viewed 9.4k times · Source

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"

Answer

David Rissato Cruz picture David Rissato Cruz · Nov 28, 2015

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.