1

I am trying to create an app and the folder structure is as so:

./
   index.js
   options/
      basic.js
      help.js

js files in the options folder will have objects like so:

ping = {
    info: 'text',
    fn: function() {}
}

I want index.js to be able to do something like

var options = require('./options');
options['ping'].fn();

How do I export/require to make it work like this? My attempts have been futile.

I want to be able to do this without a JS compiler like ES

user3916570
  • 780
  • 1
  • 9
  • 23

2 Answers2

1

You can create an index.js file inside your options folder which exports all of the sibling modules.

module.exports = {
    ping: require('./help.js'), // Assuming your "ping" object is here.
    other: require('./basic.js')
};
Marty
  • 39,033
  • 19
  • 93
  • 162
0

In the JS files (say filename.js) in your options folder use module.exports:

module.exports = {
    info: 'text',
    fn: function() {}
};

Then, to consume your module:

var options = require('./options/filename.js');
options.fn();

This is the CommonJS approach that NodeJS supports natively for modules.

You won't be able to require a folder without resorting to some other tooling, since require works at the file level.

From NodeJS's doc:

Node.js has a simple module loading system. In Node.js, files and modules are in one-to-one correspondence (each file is treated as a separate module).

Here is a good article to learn more: https://www.sitepoint.com/understanding-module-exports-exports-node-js/

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115