nodejs create tree from directories

Creating a tree from directories in Node.js is a relatively simple process that can be accomplished with a few lines of code. The basic idea is to read the directory structure, create an object with the relevant information (such as file names, path, etc), and then use it to generate an HTML structure that reflects the directory tree. Here is a basic example of how to do it: ```javascript // Load the File System module const fs = require('fs'); // Read the directory structure let directoryTree = fs.readdirSync('/path/to/directory'); // Create an object with the relevant information let treeObject = { name: '/path/to/directory', type: 'directory', items: [] }; // Recursively loop through the directory tree directoryTree.forEach(function (item) { let stats = fs.statSync(item); if (stats.isDirectory()) { treeObject.items.push({ name: item, type: 'directory', items: fs.readdirSync(item) }); } else { treeObject.items.push({ name: item, type: 'file' }); } }); // Generate the HTML structure let html = ''; function renderTree(node) { html += '

  • '; if (item.type === 'directory') { html += '' + item.name + ''; renderTree(item); } else { html += '' + item.name + ''; } html += ''; }); html += '

'; } renderTree(treeObject); // Output the HTML console.log(html); ``` This code will generate an HTML structure that looks something like this: ```html

  • folder1
  • file1.txt
  • file2.txt
  • folder2
  • file3.txt
  • file4.txt
  • file5.txt

``` This code can be adapted to create a more complex structure with additional information, such as file size, modified date, etc. You can also modify the HTML structure to match the design of your application. I hope this helps!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe