本文介紹了Node.js 遞歸列出文件的完整路徑的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
大家晚安.我可能遇到了一些簡單的遞歸函數的問題.問題是遞歸列出給定文件夾及其子文件夾中的所有文件.
Good night everyone. I'm having trouble with probably some simple recursive function. The problem is to recursively list all files in a given folder and its subfolders.
目前,我已經設法使用一個簡單的函數列出目錄中的文件:
For the moment, I've managed to list files in a directory using a simple function:
fs.readdirSync(copyFrom).forEach((file) => {
let fullPath = path.join(copyFrom, file);
if (fs.lstatSync(fullPath).isDirectory()) {
console.log(fullPath);
} else {
console.log(fullPath);
}
});
我嘗試了各種方法,例如 do{} ... while()
,但我無法做到正確.由于我是javascript的初學者,我終于決定向你們尋求幫助.
I've tried various methods like do{} ... while()
but I can't get it right. As I'm a beginner in javascript, I finally decided to ask for help from you guys.
推薦答案
只需添加一個遞歸調用即可:
Just add a recursive call and you are done:
function traverseDir(dir) {
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
console.log(fullPath);
traverseDir(fullPath);
} else {
console.log(fullPath);
}
});
}
這篇關于Node.js 遞歸列出文件的完整路徑的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!