Sometimes, we want to convert a directory structure in the filesystem to JSON with Node.js.
In this article, we’ll look at how to convert a directory structure in the filesystem to JSON with Node.js.
How to convert a directory structure in the filesystem to JSON with Node.js?
To convert a directory structure in the filesystem to JSON with Node.js, we can loop through the files and directories recursively.
For instance, we write
const fs = require('fs')
const path = require('path')
const dirTree = (filename) => {
  const stats = fs.lstatSync(filename)
  const info = {
    path: filename,
    name: path.basename(filename)
  };
  if (stats.isDirectory()) {
    info.type = "folder";
    info.children = fs.readdirSync(filename).map((child) => {
      return dirTree(`${filename}/${child}`);
    });
  } else {
    info.type = "file";
  }
  return info;
}
to define the dirTree function that gets the items in a directory with lstatSync.
Then we check if filename is a directory with stats.isDirectory.
If it is, then we call readdirSync to read the folder and call map with a callback that calls dirTree to read the directory.
Otherwise, we set info.type to 'file'.
And finally, we return info when we’re done.
Conclusion
To convert a directory structure in the filesystem to JSON with Node.js, we can loop through the files and directories recursively.