About
Module will allow you to synchronously or asynchronously import (requires) all modules from the folder you specify.
You can use modules from the returned object, or you can invoke function per file
Installation
npm i directory-import
After install, you can require module and import files:
const { directoryImport } = require('directory-import');
const importedModules = directoryImport('./');
Simple usage
This is one simple example of how to use the library and how it works under the hood:
const { directoryImport } = require('directory-import');
const importedModules = directoryImport('../sample-directory');
console.info(importedModules);
You can invoke callback on each file
This can be useful when, for example, you need to do some action depending on the imported file.
const { directoryImport } = require('directory-import');
directoryImport('../sample-directory', (moduleName, modulePath, moduleData) => {
console.info({ moduleName, modulePath, moduleData });
});
{Function} Callback:
Property | Type | Description |
---|
fileName | String | File name |
filePath | String | File path |
fileData | String | Exported file data |
index | Number | The module index |
More examples
Minimum code to run modules that are in the same folder as the code below:
const { directoryImport } = require('directory-import');
directoryImport();
Async call:
const { directoryImport } = require('directory-import');
const importedModules = directoryImport('../sample-directory', 'async');
console.info(importedModules);
Async call with callback:
const { directoryImport } = require('directory-import');
directoryImport('../sample-directory', 'async', (moduleName, modulePath, moduleData) => {
console.info({ moduleName, modulePath, moduleData });
});
Put the result in a variable and invoke a callback for each module
const { directoryImport } = require('directory-import');
const importedModules = directoryImport('../sample-directory', (moduleName, modulePath, moduleData) => {
console.info({ moduleName, modulePath, moduleData });
});
console.info(importedModules);
Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official Discord server.