Rumah > Soal Jawab > teks badan
P粉6961462052023-09-05 18:06:04
Malangnya, pilihan 异步
速度较慢。所以我们需要优化你的代码。您可以使用 {withFileTypes:true}
untuk melakukan ini adalah 2x lebih pantas.
Saya juga mencuba {recursive:true}
选项,但它甚至比您的解决方案还要慢。它不适用于 withFileTypes
dengan nod v20.
Mungkin SSD yang lebih baik dengan kelajuan bacaan tinggi akan membantu. Walaupun saya meneka entri fail dibaca dari indeks sistem fail, tidak pasti bagaimana perkakasan mempengaruhinya.
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);
Keluaran:
171.66947209835052 64508 68.24071204662323 64508