Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting name of a module in node.js

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"
like image 885
sourcevault Avatar asked Nov 27 '15 11:11

sourcevault


People also ask

What is __ filename in Node?

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

What is module object in node JS?

A module is a global object that is accessible in any NodeJs file. Node modules are reusable codes that you can create by yourself, you can use built-in ones provided by NodeJs (e.g., fs, path, os, etc.), or you can use external ones downloaded using NPM or Yarn (e.g., expressJs, mongoose, and luna).


1 Answers

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.

like image 192
David Rissato Cruz Avatar answered Sep 28 '22 07:09

David Rissato Cruz