Skip to content
Advertisement

Node.js convert directory tree to JSON

What is expected?:
I would like to convert the below listed directory structure into a single JSON file. The directory structure contains JSON files that are supposed to be included in the output file as well.

Limitations:
Node.js

Questions:
What would be a good/efficient way to generate the desired output, using Node.js + Modules? Logically, what would be the necessary steps?

Directory structure:

JavaScript

Desired output:

JavaScript

Advertisement

Answer

You could create a function to convert a directory to an object, with a property for each dir / file.

This would then be called recursively to walk the entire tree, in this case using the fs/promises functions.

JavaScript

Assuming each file looks like

JavaScript

I get a result that looks like so:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement