'why I can't get all folder's module with require('./folder')

i am using this:

index.js
functions
└abc.js
└reset.js
functions.js

functions.js

const fs = require("fs")

const functions_ = {}
const files = fs.readdirSync("./functions").filter(file => file.endsWith('.js'));

for (file of files) {
  var file_name = file
  file_name = file_name.substr(0,file_name.search("\\."))
  functions_[file_name] = require(`./functions/${file}`)
};

module.exports = functions_

In short, I create a function with that folder name for each folder. i tried this code to make it much easier

require('./functions');

but it didn't work

Isn't there a way to make this much easier? (The title may be wrong, I couldn't find what title to put.)



Solution 1:[1]

The short answer is no.

For the long answer: You can't because require/import statements in all languages are configured to import files and not folders. So you can't require a folder because the folder technically doesn't have valid readable/executable code. But when you require/import a file in JavaScript, the exported parts of that file can be used in the "importee" file (the file from which other files are being imported).

No matter the number of files, you need to statically import them as you need them.

Proposed Solution

You can import everything in that folder into an index.js file in that very folder. Then import everything from ./folder/index, that can work too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1