Skip to content
the poor coder

nodejs create tree from directories

Poor Man
Published
Reading time
1 min read

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!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC