Module sync or async import(requires) all modules from the folder you specify.
It's possible either to use modules from the returned object, or to execute a callback at each iteration
Installation
npm i directory-import
After install, you can require module:
const importDir = require('directory-import');
Usage
For example, we have the following directory structure:
In the code below, we gave several examples of how to import all modules into "someDir" directory and all its subdirectories.
const importDir = require('directory-import');
importDir(`./someDir`, 'sync');
importDir(`./someDir`, 'sync', (name, path, func) => {
console.info(
`name: ${name} \n` +
`path: ${path} \n` +
`func: ${func} \n`
);
});
importDir(`./someDir`, 'async', (name, path, func) => {
console.info(
`name: ${name} \n` +
`path: ${path} \n` +
`func: ${func} \n`
);
});
const modulesSync = importDir(`./someDir`, 'sync');
console.info(modulesSync);
const modulesAsync = importDir(`./someDir`, 'async');
setTimeout(() => {
console.info(modulesAsync);
}, 1000);
You can easily combine this methods.
const modules = importDir(`./someDir`, 'sync', (name, path, func) => {
console.info(
`name: ${name} \n` +
`path: ${path} \n` +
`func: ${func} \n`
);
});
console.info(modules);