I'm trying to get my head around NodeJS by writing a few test apps. I've managed okay so far but the one thing that's tripping me up is the following.
I've got it reading a directory for folders, and then parsing the settings.json files within each folder (so I can build a UI on the fly based on the folder contents). The problem is, I can't seem to "step down a level" with the JSON object.
For example, coming from a background in php where you could do something like the following to 'step' through the array:
<?php
$arr = [
'folder1' =>
[ 'name' => 'test',
'icon' => 'icon-test'
],
'folder2' =>
[ 'name' => 'test-2',
'icon' => 'icon-test-2'
]
];
foreach($arr as $k => $v){
// folder1 level
foreach($v as $k2 => $v2){
// name / icon level.
echo $k2 . ' is ' . $v2;
}
}
?>
Is there an equivalent in JS? I can do the first "level" by doing this:
function getDirectories (srcpath) {
return fs.readdirSync(srcpath)
.filter(file => fs.lstatSync(path.join(srcpath, file)).isDirectory())
}
var d = getDirectories('modules');
var modules = {};
// the following reads the json in each dir into an object like:
// { 'dirname': { 'key1': 'val1', 'key2': 'val2' }, 'dirname2'... }
for(var p in d){
modules[d[p]] = JSON.parse(fs.readFileSync('./modules/'+d[p]+'/config.json', 'utf8'));
}
for(var k in modules){
console.log(k);
}
But ideally I need to extract "name" and "icon" from the JSON. I can't seem to find any way of doing this.
I understand this is probably messy but I'm just getting my head around NodeJS. For full clarity, directory structure and my simple JSON files below:
modules directory structure
modules
|____ test
|____ config.json
|____ test-2
|____ config.json
config.json (example)
{
"name": "test",
"icon": "test-icon"
}