1

Anty body did write file names in a folder to the CSV file using javascript

my folder structure is

Data
 +IMG
    +test
       -1.png
       -2.png
    +train
       -3.png
       -4.png

an output CSV file will be like this

Data/IMG/test/1.png     Data/IMG/train/3.png
Data/IMG/test/2.png     Data/IMG/train/4.png
Shan
  • 180
  • 1
  • 2
  • 13

1 Answers1

0

You just need to loop through all folders and find all files. You can refer to this answer to do this.

when you are finding all files' paths, you can write these paths in a string for the csv file:

const fs = require('fs');
const path = require('path');

let csvStr = "";

async function loop(startPath) {
    // Our starting point
    try {
        // Get the files as an array
        const files = await fs.promises.readdir(startPath);

        // Loop them all with the new for...of
        for (const file of files) {
            // Get the full paths
            const currentPath = path.join(startPath, file);

            // Stat the file to see if we have a file or dir
            const stat = await fs.promises.stat(currentPath);

            if (stat.isFile()) {
                console.log("'%s' is a file.", currentPath);
                // put the file into csv string
                csvStr += currentPath + ", "
            } else if (stat.isDirectory()) {
                console.log("'%s' is a directory.", currentPath);
                // enter the dictionary and loop
                await loop(currentPath);
            }

        } // End for...of
    } catch (e) {
        // Catch anything bad that happens
        console.error("We've thrown! Whoops!", e);
    }

}

// Make an async function that gets executed immediately
(async () => {
    // start loop from the path where you run node
    await loop("./");

    fs.writeFileSync("your.csv", csvStr);
})();
tigercosmos
  • 345
  • 3
  • 17
  • Thanks for your reply I am new to js can you explain a bit more or make the code – Shan Aug 13 '20 at 20:40
  • `fromPath` is the inner loop is the current position in the folders which should be a file's path or a dictionary's path. You want to find all files, so we just need the files' paths. We can collect the files paths' name for CSV, so I add `csvStr += fromPath + ", "`. `,` is for the CSV seperator. – tigercosmos Aug 13 '20 at 20:46
  • can you provide a full of code bro? I have tried but not get successful – Shan Aug 14 '20 at 06:19
  • there are always commas in CSV (Comma-separated values) file, so I cannot understand your given sample output (no commas). Or, I guess you just want the `test` to be a column and `train` to be another one? I thought it's not too hard, since you have already know how to get all files name. What you need to do is adding some `if else`, would you like to try yourself? – tigercosmos Aug 14 '20 at 10:17