2

In my Node.js app, after I require all my modules into my server.js, then I am passing their instances into my function. My function needs to figure out which module is passed and it will call corresponding file.

I tried to get module name by following way but I could not get it done.

Is there any way to extract module name? It can be object name as well.

this is my server js file

var less = require("less");
var express = require("express");
var path = require('path');
var MyApp = require("./LocalModules/MyApp.js");
MyApp.InitializeAll([less, express]);

And this is where I need to resolve module name.

exports.InitializeAll = function (modules) {
    for (var i = 0; i < modules.length; i++) {
        var currentModule = modules[i];
        var localModuleName = "MyApp_" + currentModule.constructor.name + ".js";
        var appModule = require(localModuleName);
        appModule.Initialize(currentModule);
    };

}

1 Answer 1

1

Why not pass the modules as an object, that way you can just get the keys

MyApp.InitializeAll({less : less, express : express});

and then do

exports.InitializeAll = function (modules) {

    for (var module in modules) {

        var currentModule   = modules[module];
        var localModuleName = "MyApp_" + module + ".js";
        var appModule       = require(localModuleName);

        appModule.Initialize(currentModule);
    };

}
Sign up to request clarification or add additional context in comments.

1 Comment

This is correct, thanks for pointing this out, already works :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.