Getting name of a module in node.js

2019-06-22 19:22发布

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"

3条回答
倾城 Initia
2楼-- · 2019-06-22 19:47

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 children 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(childModule);

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 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 where discoverChildModule function resides (if it is in the same file won't make any diference, 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.
查看更多
成全新的幸福
3楼-- · 2019-06-22 19:56

From within a module (doesn't work at the REPL) you can...

console.log( global.process.mainModule.filename );

And you'll get '/home/ubuntu/workspace/src/admin.js'

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-06-22 19:57

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.

查看更多
登录 后发表回答