NodeJS đọc dir đệ quy

Để tạo một số loại thuật toán tìm kiếm tệp hoặc để lấy danh sách tất cả các tệp và thư mục bên trong một thư mục để nén nó bằng zlib, tính năng này thường được tìm kiếm cho Nút. js (và số lượt tải xuống và các gói phụ thuộc trên một số mô-đun đã biết đã chứng minh điều đó)

Trong bài viết này, chúng tôi sẽ chỉ cho bạn cách lặp đệ quy qua một thư mục để liệt kê tất cả nội dung của thư mục đó bằng 3 phương pháp khác nhau (đoạn mã tùy chỉnh hoặc bằng cách sử dụng các mô-đun nguồn mở)

A. Sử dụng đoạn mã tùy chỉnh

Nếu bạn muốn lặp đệ quy qua một thư mục trong Node. js, bạn không nhất thiết phải có một mô-đun để đạt được điều đó vì bạn có thể sử dụng một hàm đệ quy rất đơn giản. Hàm

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
2 sau đây sẽ thực hiện thủ thuật cho bạn. Nó mong đợi đối số đầu tiên là một chuỗi có đường dẫn của thư mục sẽ được khám phá theo cách đệ quy và đối số thứ hai là một hàm (gọi lại) được thực thi khi không có thư mục nào bên trong đường dẫn đã cung cấp. Cuộc gọi lại nhận được 2 đối số, lỗi là đầu tiên và mảng kết quả chứa tất cả các đường dẫn hỗn hợp của tệp và thư mục con

Ghi chú

Nếu bạn chỉ cần bỏ qua tất cả các thư mục và chỉ truy xuất đường dẫn của tệp, bạn có thể dễ dàng nhận xét dòng lưu trữ đường dẫn tệp trong mảng trong đoạn mã

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

/**
 * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
 * 
 * @see http://stackoverflow.com/a/5827895/4241030
 * @param {String} dir 
 * @param {Function} done 
 */
function filewalker(dir, done) {
    let results = [];

    fs.readdir(dir, function(err, list) {
        if (err) return done(err);

        var pending = list.length;

        if (!pending) return done(null, results);

        list.forEach(function(file){
            file = path.resolve(dir, file);

            fs.stat(file, function(err, stat){
                // If directory, execute a recursive call
                if (stat && stat.isDirectory()) {
                    // Add directory to array [comment if you need to remove the directories from the array]
                    results.push(file);

                    filewalker(file, function(err, res){
                        results = results.concat(res);
                        if (!--pending) done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) done(null, results);
                }
            });
        });
    });
};

Và cách sử dụng nó rất đơn giản

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});

Giải pháp này hoàn hảo nếu bạn không muốn dựa vào một mô-đun để đạt được điều gì đó rất đơn giản và trực tiếp trong mã của mình

B. Sử dụng mô-đun readdirp

Nếu mã của bạn không đơn giản như vậy, thì giải pháp với một đoạn mã duy nhất có thể không đủ cho bạn do độ phức tạp của mã. Trong trường hợp này, bạn có thể sử dụng mô-đun

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
3, có
filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
3 chứ không phải
filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
5. readdirp là một mô-đun rất hữu ích hiển thị phiên bản đệ quy của hàm
filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
5 có sẵn trong mô-đun hệ thống tệp của Node. js, bên cạnh đó, nó hiển thị một luồng api

Để cài đặt mô-đun này trong dự án của bạn, hãy thực hiện lệnh sau trong thiết bị đầu cuối của bạn

npm install readdirp

Ưu điểm của việc sử dụng mô-đun này là rất rõ ràng và nó không đơn giản như giải pháp đầu tiên mà chúng tôi trình bày trong bài viết này. Mô-đun này cho phép bạn lọc khám phá đệ quy của mình theo phần mở rộng tệp và theo tên thư mục, bên cạnh đó, nó cho phép bạn đặt độ sâu (giá trị tối đa của các thư mục con để khám phá trong thư mục được cung cấp). Nó hoạt động theo cách sau, bạn cần yêu cầu mô-đun readdirp về cơ bản là một chức năng. Với chức năng này, bạn sẽ có thể lặp lại đệ quy thông qua đường dẫn thư mục, nó yêu cầu một đối tượng chỉ định cài đặt,

________số 8

Về cơ bản, bạn chỉ cần cung cấp thuộc tính gốc cho biết thư mục nào sẽ được khám phá

Mô-đun cung cấp 2 cách để sử dụng, cách đầu tiên là với các cuộc gọi lại

// Import the module
var readdirp = require('readdirp');

var settings = {
    root: './your-folder-path',
    entryType: 'all'
};

// In this example, this variable will store all the paths of the files and directories inside the providen path
var allFilePaths = [];

// Iterate recursively through a folder
readdirp(settings,
    // This callback is executed everytime a file or directory is found inside the providen path
    function(fileInfo) {
        
        // Store the fullPath of the file/directory in our custom array 
        allFilePaths.push(
            fileInfo.fullPath
        );
    }, 

    // This callback is executed once 
    function (err, res) {
        if(err){
            throw err;
        }

        // An array with all the fileEntry objects of the folder 
        // console.log(res);
        console.log(allFilePaths);
        // ["c:/file.txt",""]
    }
);

Hoặc thông qua API luồng

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

/**
 * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
 * 
 * @see http://stackoverflow.com/a/5827895/4241030
 * @param {String} dir 
 * @param {Function} done 
 */
function filewalker(dir, done) {
    let results = [];

    fs.readdir(dir, function(err, list) {
        if (err) return done(err);

        var pending = list.length;

        if (!pending) return done(null, results);

        list.forEach(function(file){
            file = path.resolve(dir, file);

            fs.stat(file, function(err, stat){
                // If directory, execute a recursive call
                if (stat && stat.isDirectory()) {
                    // Add directory to array [comment if you need to remove the directories from the array]
                    results.push(file);

                    filewalker(file, function(err, res){
                        results = results.concat(res);
                        if (!--pending) done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) done(null, results);
                }
            });
        });
    });
};
0

Mỗi đối tượng

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
7, có cấu trúc như sau, vì vậy bạn sẽ nhận được không chỉ đường dẫn đầy đủ mà còn nhiều thông tin hữu ích hơn về tệp hoặc thư mục

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

/**
 * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
 * 
 * @see http://stackoverflow.com/a/5827895/4241030
 * @param {String} dir 
 * @param {Function} done 
 */
function filewalker(dir, done) {
    let results = [];

    fs.readdir(dir, function(err, list) {
        if (err) return done(err);

        var pending = list.length;

        if (!pending) return done(null, results);

        list.forEach(function(file){
            file = path.resolve(dir, file);

            fs.stat(file, function(err, stat){
                // If directory, execute a recursive call
                if (stat && stat.isDirectory()) {
                    // Add directory to array [comment if you need to remove the directories from the array]
                    results.push(file);

                    filewalker(file, function(err, res){
                        results = results.concat(res);
                        if (!--pending) done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) done(null, results);
                }
            });
        });
    });
};
2

Để biết thêm thông tin, vui lòng truy cập kho lưu trữ mô-đun trên Github tại đây

C. Sử dụng các mô-đun klaw và klaw-sync

Ban đầu, nhiều nhà phát triển đã từng dựa vào mô-đun cờ lê (và nhiều người vẫn dựa vào), tuy nhiên, hiện tại mô-đun này đã chính thức bị phản đối và chúng tôi muốn thúc đẩy các tiêu chuẩn, bạn không nên sử dụng mô-đun này nữa (chúng tôi không cấm, vì vậy, vui lòng . Dự án hiện khuyến nghị sử dụng mô-đun fs-extra, tuy nhiên, mô-đun này không hỗ trợ các hàm

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
8 và
filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
9 nữa (lý do tại sao các nhà phát triển đã sử dụng mô-đun cờ lê để khám phá một thư mục theo cách đệ quy)

Vì các hàm đệ quy không còn khả dụng nữa, nên mô-đun fs-extra khuyến nghị sử dụng mô-đun klaw. Mô-đun này hiển thị một Nút không đồng bộ. trình hướng dẫn hệ thống tệp js với giao diện luồng có thể đọc được được trích xuất ban đầu từ mô-đun fs-extra

Để cài đặt mô-đun này, hãy thực hiện lệnh sau trong thiết bị đầu cuối của bạn

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

/**
 * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
 * 
 * @see http://stackoverflow.com/a/5827895/4241030
 * @param {String} dir 
 * @param {Function} done 
 */
function filewalker(dir, done) {
    let results = [];

    fs.readdir(dir, function(err, list) {
        if (err) return done(err);

        var pending = list.length;

        if (!pending) return done(null, results);

        list.forEach(function(file){
            file = path.resolve(dir, file);

            fs.stat(file, function(err, stat){
                // If directory, execute a recursive call
                if (stat && stat.isDirectory()) {
                    // Add directory to array [comment if you need to remove the directories from the array]
                    results.push(file);

                    filewalker(file, function(err, res){
                        results = results.concat(res);
                        if (!--pending) done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) done(null, results);
                }
            });
        });
    });
};
5

Klaw rất dễ sử dụng và có thể tùy chỉnh. Để lặp đệ quy qua một thư mục, hãy sử dụng đoạn mã sau

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

/**
 * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
 * 
 * @see http://stackoverflow.com/a/5827895/4241030
 * @param {String} dir 
 * @param {Function} done 
 */
function filewalker(dir, done) {
    let results = [];

    fs.readdir(dir, function(err, list) {
        if (err) return done(err);

        var pending = list.length;

        if (!pending) return done(null, results);

        list.forEach(function(file){
            file = path.resolve(dir, file);

            fs.stat(file, function(err, stat){
                // If directory, execute a recursive call
                if (stat && stat.isDirectory()) {
                    // Add directory to array [comment if you need to remove the directories from the array]
                    results.push(file);

                    filewalker(file, function(err, res){
                        results = results.concat(res);
                        if (!--pending) done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) done(null, results);
                }
            });
        });
    });
};
6

Vì nó không đồng bộ, bạn cần dựa vào cuộc gọi lại kết thúc để làm bất cứ điều gì bạn muốn với danh sách các tệp và thư mục được tìm thấy trong thư mục được cung cấp

Để biết thêm thông tin về mô-đun klaw không đồng bộ, vui lòng truy cập kho lưu trữ chính thức trên Github tại đây

Nếu bạn cần chức năng tương tự nhưng đồng bộ, bạn có thể sử dụng mô-đun klaw-sync. klaw-sync là một Nút. js đệ quy hệ thống tập tin walker, là bản sao đồng bộ của klaw. Nó liệt kê tất cả các tệp và thư mục bên trong một thư mục theo cách đệ quy và trả về một mảng các đối tượng mà mỗi đối tượng có hai thuộc tính.

npm install readdirp
0 và
npm install readdirp
1. đường dẫn là đường dẫn đầy đủ của tệp hoặc thư mục và số liệu thống kê là một phiên bản của
npm install readdirp
2

Để cài đặt mô-đun này, hãy thực hiện lệnh sau trong thiết bị đầu cuối của bạn

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
0

Phiên bản đồng bộ của klaw rất dễ sử dụng như phiên bản không đồng bộ, tuy nhiên nó có thể tùy chỉnh nhiều hơn so với phiên bản tương ứng của nó. Bạn có thể sử dụng đoạn mã sau để khám phá một thư mục

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
0

klaw-sync cho phép bạn lọc các thư mục và tệp theo phần mở rộng, tên. Bên cạnh đó, bạn chỉ có thể tìm kiếm các thư mục hoặc tệp theo

filewalker("./some-existent-path", function(err, data){
    if(err){
        throw err;
    }
    
    // ["c://some-existent-path/file.txt","c:/some-existent-path/subfolder"]
    console.log(data);
});
1

Để biết thêm thông tin về mô-đun klaw đồng bộ, vui lòng truy cập kho lưu trữ chính thức trên Github tại đây

Klaw là viết tắt của walk (nhưng ngược lại) và hóa ra (kể từ ngày 25 tháng 1 năm 2017) trong hầu hết các trường hợp, klaw và klaw-sync nhanh hơn các mô-đun khác

Làm cách nào để đọc tất cả các tệp trong một thư mục trong nút js?

Nhận danh sách tất cả các tệp trong một thư mục trong Node. .
fs. readdir(path, callbackFunction) — Phương thức này sẽ đọc tất cả các tệp trong thư mục. Bạn cần chuyển đường dẫn thư mục làm đối số đầu tiên và trong đối số thứ hai, bạn có thể sử dụng bất kỳ hàm gọi lại nào
con đường. tham gia () - Phương thức nút này

Làm cách nào để lấy tất cả các tệp từ thư mục và thư mục con trong JavaScript?

js cung cấp fs. readdir() để lấy tất cả các tệp có trong một thư mục. Nếu thư mục mẹ chứa các thư mục con, bạn có thể quét các thư mục con đó để lấy tệp theo cách đệ quy. .
Nhập nút cần thiết. .
Truyền các đối số đường dẫn và tùy chọn trong phương thức readdir(path, options)

Làm cách nào để sử dụng __ Dirname trong nút JS?

__dirname trong tập lệnh nút trả về đường dẫn của thư mục chứa tệp JavaScript hiện tại . __filename và __dirname được sử dụng để lấy tên tệp và tên thư mục của tệp hiện đang thực thi. Các. / đưa ra thư mục làm việc hiện tại. Nó hoạt động tương tự như quá trình.

Làm cách nào để đọc tệp trong nút js?

Nút. js với tư cách là Máy chủ tệp . var fs = yêu cầu('fs'); . đọc tập tin. use the require() method: var fs = require('fs'); Common use for the File System module: Read files.