[Node.js] 學習筆記:使用 readdir() 尋訪目錄下所有檔案

[Node.js] 學習筆記:使用 readdir() 尋訪目錄下所有檔案

Learnyounode 的第五課,是用 readdir() 以非同步方式取得目錄下的所有檔案~

簡單範例如下:

var fs = require("fs");
fs.readdir(process.argv[2], function(err, list) {
console.log(list);
});

 

如果想要遞迴列出所有子目錄下的東西,先用 fs.stat() 判斷一下是否為目錄,

再往下走就行了:

var fs = require("fs");
var path = require("path");
function visit_dir(dir)
{
// Print folder name
console.log("\n[" + dir + "]");
fs.readdir(dir, function(err, files) {
if (!err)
{
files.forEach(function(file) {
// Print file name
console.log(file);
file_full_path = path.join(dir, file);
// Get file stat
fs.stat(file_full_path, function(err, stats) {
console.log(file_full_path);
if (!err && stats.isDirectory())
{
visit_dir(file_full_path);
}
});
});
}
});
}
visit_dir(process.argv[2]);

 

不過上面的程式執行後,卻發現 file_full_path 有點怪怪的,

值都是最後一個檔案的名稱,在本例中是 webserver.js:

testuser@localhost ~ $ node visit_dir.js .
[.]
NodeSchool
echo_server.js
module_path.js
read_file.js
visit_dir.js
webserver.js
file_full_path=webserver.js
[webserver.js]
file_full_path=webserver.js
file_full_path=webserver.js
file_full_path=webserver.js
file_full_path=webserver.js
file_full_path=webserver.js

 

這是因為 file_full_path 的值在 forEach 迴圈中一直被修改,

最後就是保留最後一次的值了~

而 fs.stat() 的 callback function 在那之後才會被呼叫到,

因此拿到的都是固定的最後一次的值…

 

要解決這個問題,一個方法是使用 IIFE (Immediately Invoked Function Expression),

如 JavaScript Cookbook: Preserving variables inside async calls called in a loop

修改後程式如下:

var fs = require("fs");
var path = require("path");
function visit_dir(dir)
{
fs.readdir(dir, function(err, files) {
if (!err)
{
// Print folder name
console.log("\n[" + dir + "]");
files.forEach(function(file) {
// Print file name
console.log(file);
file_full_path = path.join(dir, file);
(function(file_full_path) {
// Get file stat
fs.stat(file_full_path, function(err, stats) {
console.log("file_full_path="+file_full_path);
if (!err && stats.isDirectory())
{
visit_dir(file_full_path);
}
});
})(file_full_path);
});
}
});
}
visit_dir(process.argv[2]);

 

執行結果也就正常囉:

testuser@localhost ~ $ node visit_dir.js .
[.]
NodeSchool
echo_server.js
module_path.js
read_file.js
visit_dir.js
webserver.js
file_full_path=NodeSchool
file_full_path=echo_server.js
file_full_path=module_path.js
file_full_path=read_file.js
file_full_path=visit_dir.js
file_full_path=webserver.js
[NodeSchool]
01_hello_world.js
02_argv_sum.js
03_count_newline.js
04_count_newline_async.js
05_list_files_by_ext.js
file_full_path=NodeSchool/01_hello_world.js
file_full_path=NodeSchool/02_argv_sum.js
file_full_path=NodeSchool/03_count_newline.js
file_full_path=NodeSchool/04_count_newline_async.js
file_full_path=NodeSchool/05_list_files_by_ext.js

 

 

 

(本頁面已被瀏覽過 3,240 次)

One thought on “[Node.js] 學習筆記:使用 readdir() 尋訪目錄下所有檔案

  1. 你的目錄輸出,與檔案輸出順序會不同,上面結果應該是運氣好,所以排得很整齊…
    版主回覆:(04/29/2015 09:49:33 AM)
    感謝您的指正,我後來看程式的確會有這樣的問題,會再把它修正一下,謝謝~~

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料