国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

fs.readdirSync 有多快?我可以加快速度嗎?
P粉064448449
P粉064448449 2023-09-04 19:48:56
0
1
782
<p>我有一個函數(shù),可以使用 fs.readdirSync 遞歸地獲取目錄中的所有文件。 它與我作為測試運(yùn)行的小目錄配合得很好,但現(xiàn)在我在一個超過 100GB 的目錄上運(yùn)行它,需要很長時間才能完成。關(guān)于如何加快速度或者是否有更好的方法,有什么想法嗎?我最終將不得不在一些包含 TB 數(shù)據(jù)的目錄上運(yùn)行它。</p> <pre class="brush:php;toolbar:false;">// Recursive function to get files function getFiles(dir, files = []) { // Get an array of all files and directories in the passed directory using fs.readdirSync const fileList = fs.readdirSync(dir); // Create the full path of the file/directory by concatenating the passed directory and file/directory name for (const file of fileList) { const name = `${dir}/${file}`; // Check if the current file/directory is a directory using fs.statSync if (fs.statSync(name).isDirectory()) { // If it is a directory, recursively call the getFiles function with the directory path and the files array getFiles(name, files); } else { // If it is a file, push the full path to the files array files.push(name); } } return files; }</pre></p>
P粉064448449
P粉064448449

全部回復(fù)(1)
P粉696146205

不幸的是,異步速度較慢。所以我們需要優(yōu)化你的代碼。您可以使用 {withFileTypes:true} 選項(xiàng)來完成此操作,速度提高 2 倍。

我還嘗試過節(jié)點(diǎn) v20 的 {recursive:true} 選項(xiàng),但它甚至比您的解決方案還要慢。它不適用于 withFileTypes。

也許具有高讀取速度的更好 SSD 會有所幫助。雖然我猜文件條目是從文件系統(tǒng)索引讀取的,但不確定硬件如何影響它。

import fs from 'fs';

const DIR = '/bytex';

function getFiles(dir, files = []) {
    // Get an array of all files and directories in the passed directory using fs.readdirSync
    const fileList = fs.readdirSync(dir);
    // Create the full path of the file/directory by concatenating the passed directory and file/directory name
    for (const file of fileList) {
        const name = `${dir}/${file}`;
        // Check if the current file/directory is a directory using fs.statSync
        if (fs.statSync(name).isDirectory()) {
            // If it is a directory, recursively call the getFiles function with the directory path and the files array
            getFiles(name, files);
        } else {
            // If it is a file, push the full path to the files array
            files.push(name);
        }
    }
    return files;
}

function getFiles2(dir, files = []) {
    const fileList = fs.readdirSync(dir, { withFileTypes: true });
    fileList.forEach(file => file.isDirectory() ? getFiles2(`${dir}/${file.name}`, files) : files.push(`${dir}/${file.name}`));
    return files;
}

let start = performance.now();
let files = getFiles(DIR);
console.log(performance.now() - start);
console.log(files.length);

start = performance.now();
files = getFiles2(DIR);
console.log(performance.now() - start);
console.log(files.length);

輸出:

171.66947209835052
64508
68.24071204662323
64508
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板