亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用Nodejs將文件夾中的數據作為文件名寫入CSV文件

如何使用Nodejs將文件夾中的數據作為文件名寫入CSV文件

qq_花開花謝_0 2023-01-06 11:24:50
Anty body確實使用javascript將文件夾中的文件名寫入CSV文件我的文件夾結構是Data  +IMG     +test        -1.png        -2.png     +train        -3.png        -4.png輸出 CSV 文件將是這樣的Data/IMG/test/1.png     Data/IMG/train/3.png Data/IMG/test/2.png     Data/IMG/train/4.png
查看完整描述

1 回答

?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

您只需要遍歷所有文件夾并找到所有文件。您可以參考此答案來執行此操作。


當您找到所有文件的路徑時,您可以將這些路徑寫入 csv 文件的字符串中:


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);

})();


查看完整回答
反對 回復 2023-01-06
  • 1 回答
  • 0 關注
  • 184 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號