最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js, require all modules in folder and use loaded module directly - Stack Overflow

programmeradmin2浏览0评论

In MyModule folder, I have this two JS files.

SayHello.js

module.exports.SayHello = function() {
    return('Hello !');
}

SayByeBye.js

module.exports.SayByeBye = function() {
    return('Bye Bye!');
}

In Node.js, I want to require all files in MyModule folder and call function SayHello & SayByeBye directly something like:

require(./MyModule) 
console.log(SayHello());
console.log(SayByeBye());

EDIT:

With answer of @Yanick Rochon,I do this :

> ./app/my-module/index.js

global.SayHello = require('./my-module/SayHello').SayHello;
global.SayByeBye = require('./my-module/SayByeBye').SayByeBye;

> ./app/my-module/say-hello.js

module.exports.SayHello = function() {
    return('Hello !');
};

> ./app/my-module/say-byebye.js

module.exports.SayByeBye = function() {
    return('Bye Bye !');
};

> ./app/main.js

require('./my-module');
console.log(SayHello());
console.log(SayByeBye());

There's a section about global objects in the node documentation.

However, globals should be used with care. By adding modules to the global space I reduce testability and encapsulation. But in this case, I think using this method is acceptable.

In MyModule folder, I have this two JS files.

SayHello.js

module.exports.SayHello = function() {
    return('Hello !');
}

SayByeBye.js

module.exports.SayByeBye = function() {
    return('Bye Bye!');
}

In Node.js, I want to require all files in MyModule folder and call function SayHello & SayByeBye directly something like:

require(./MyModule) 
console.log(SayHello());
console.log(SayByeBye());

EDIT:

With answer of @Yanick Rochon,I do this :

> ./app/my-module/index.js

global.SayHello = require('./my-module/SayHello').SayHello;
global.SayByeBye = require('./my-module/SayByeBye').SayByeBye;

> ./app/my-module/say-hello.js

module.exports.SayHello = function() {
    return('Hello !');
};

> ./app/my-module/say-byebye.js

module.exports.SayByeBye = function() {
    return('Bye Bye !');
};

> ./app/main.js

require('./my-module');
console.log(SayHello());
console.log(SayByeBye());

There's a section about global objects in the node documentation.

However, globals should be used with care. By adding modules to the global space I reduce testability and encapsulation. But in this case, I think using this method is acceptable.

Share Improve this question edited May 23, 2017 at 12:13 CommunityBot 11 silver badge asked Jul 27, 2015 at 15:37 LeMousselLeMoussel 5,76715 gold badges77 silver badges129 bronze badges 6
  • You shouldn't put the module before exports, instead simply do exports.SayHello = function..... see here stackoverflow./questions/31657341/… – Daniel Kobe Commented Jul 27, 2015 at 15:59
  • Daniel, the link is this post ? – LeMoussel Commented Jul 27, 2015 at 16:02
  • @LeMoussel oops stackoverflow./questions/7137397/… – Daniel Kobe Commented Jul 27, 2015 at 16:33
  • Not related, but why are your file names reversed? Its bothering me more than I would care to admit. – bluesman Commented Jul 27, 2015 at 18:22
  • 1 There must be a mistake. I corrected. – LeMoussel Commented Jul 27, 2015 at 18:50
 |  Show 1 more ment

2 Answers 2

Reset to default 6

First thing first...

I believe you are mistaking Node.js with PHP or .Net, in the sense that you don't "import" into the current module what is exported in other modules. Not unless you manually do it anyway. For example, when you call

require('./my-module');

(Note that I renamed your MyModule into Node.js naming convention.)

You don't load things into the current context; you just load the script and don't assign it to anything. To access what my-module exposes, you need to assign it, or use it directly. For example :

require('./my-module').someFunction();

or

var myModule = require('./my-module');

myModule.someFunction();

Modules are not namespaces, but JavaScript objects that exposes public properties outside of their own contexts (i.e. using module.exports = ...)

Answer

You have two most popular ways to acplish this :

Solution 1

Create an index.json file inside your folder where you want to load all of your scripts. The returned JSON object should be all the modules to load automatically :

> ./app/index.json

[
  "say-hello.js",
  "say-goodbye.js"
]

You should also consider having all your files API patible :

> ./app/say-hello.js

module.exports = function sayHello() {
  return 'Hello !';
};

> ./app/say-goodbye.js

module.exports.sayGoodbye = function () {
  return 'Goodbye !';
};

Then load and execute everything like this :

var path = require('path');
var basePath = './app/';

var files = require(basePath);

var mods = files.forEach(function (loaded, file) {
  var mod = require(path.join(basePath, file));

  // mod is a function with a name, so use it!
  if (mod instanceof Function) {
    loaded[mod.name] = mod;
  } else {
    Object.keys(mod).forEach(function (property) {
      loaded[property] = mod.property;
    });
  }
}, {});

mods.sayHello();
mods.sayGoodbye();

Solution 2

Read all .js files inside your folder and import them. I highly remend you use glob for this.

var glob = require("glob")
var path = require('path');
var basePath = './app/';

var mods = glob.sync(path.join(basePath, '*.js')).reduce(function (loaded, file) {
  var mod = require(file);

  // mod is a function with a name, so use it!
  if (mod instanceof Function) {
    loaded[mod.name] = mod;
  } else {
    Object.keys(mod).forEach(function (property) {
      loaded[property] = mod.property;
    });
  }

  return loaded;
}, {});

mods.sayHello();
mods.sayGoodbye();

Note on the difference between module.exports and exports

Typically module.exports === exports, but it is remended to use module.exports for the following reason

exports = function Foo() { }         // will not do anything
module.exports = function Foo() { }  // but this will do what you expect

// however these two lines produce the same result
exports.foo = 'Bar';
module.exports.foo = 'Bar';  

For this reason, module.exports is remended in all cases.

It's not perfect, but something like this should help you acplish this:

var fs = require('fs');
var path = require('path');

var files = fs.readdirSync(__dirname);
var ownFilename = __filename.substr(__filename.lastIndexOf(path.delimiter) + 1);

var modules = {};
for (var i = 0; i < files.length; i++) {
        var filename = files[i];
        if (filename.substr(-3) === '.js' && filename !== ownFilename) {
                modules[filename.slice(0, -3)] = require('./' + filename);
        }
}

console.log(modules.SayByeBye());
console.log(modules.SayHello());

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论