Recursively loads content of found JavaScript and JSON files in given directory into a single structured object
This module recursively loads exported content of all *.js
and *.json
files (configurable via extensions
) found in
given directory
using given fileLoader
(defaults to require
) creating a single object that preservers the file
structure of the loaded content as the property path, transforming the file and folder names using given
pathTransformer
function (defaults to
lodash→camelCase).
Useful to split what could be a big configuration object into a file / folder structure.
Take the following file structure:
<directory>
├── users/
│ ├── index.js
│ ├── maria.json
│ ├── martin.js
│ └── maria.json
└── some-config.json
users/index.js
module.exports = {
'some-guy': 'Un-altered'
}
users/maria.json
{
"name": "Maria",
"email": "[email protected]"
}
users/martin.js
module.exports = {
name: "Martin",
email: "[email protected]"
}
some-config.js (see esm support below)
export default {
plugins: [
'plugin-1',
'plugin-2'
]
}
And the following script:
const { jsDirIntoJson } = require('js-dir-into-json')
jsDirIntoJson('<directory>',
{
// extensions: ['*.js', '*.json'], // minimatch or RegExp
// pathTransformer: default to lodash camelCase
// fileLoader: default to require (or fileLoader = require('esm')(module) for esm support)
}
).then(obj => {
t.deepEquals(obj, {
"users": {
"maria": {
"name": "Maria",
"email": "[email protected]"
},
"martin": {
"name": "Martin",
"email": "[email protected]"
},
"olivia": "thats me!",
"some-guy": "Un-altered"
},
"someConfig": {
"plugins": [
"plugin-1",
"plugin-2"
]
}
});
});
© 2020-present Martin Rafael Gonzalez [email protected]