Для рекурсивного поиска определенного файла в каталогах и подкаталогах в Node.js вы можете использовать модуль fs
(файловая система) и функцию readdirSync()
. Эта функция считывает содержимое каталога и возвращает массив имен файлов и каталогов в каталоге. Затем вы можете использовать рекурсивную функцию для поиска в каталогах и подкаталогах.
Ниже приведен пример того, как это можно сделать в Node.js.
const fs = require('fs'); function searchFile(dir, fileName) { // read the contents of the directory const files = fs.readdirSync(dir); // search through the files for (const file of files) { // build the full path of the file const filePath = path.join(dir, file); // get the file stats const fileStat = fs.statSync(filePath); // if the file is a directory, recursively search the directory if (fileStat.isDirectory()) { searchFile(filePath, fileName); } else if (file.endsWith(fileName)) { // if the file is a match, print it console.log(filePath); } } } // start the search in the current directory searchFile('./', 'example.txt');
В JavaScript вы можете использовать модуль fs
и функцию readdir()
аналогичным образом для рекурсивного поиска определенного файла в каталогах и подкаталогах. Функция readdir()
работает асинхронно, поэтому вам потребуется использовать функцию обратного вызова для обработки результатов функции.
Вот пример того, как вы можете сделать это в JavaScript:
const fs = require('fs'); function searchFile(dir, fileName) { // read the contents of the directory fs.readdir(dir, (err, files) => { if (err) throw err; // search through the files for (const file of files) { // build the full path of the file const filePath = path.join(dir, file); // get the file stats fs.stat(filePath, (err, fileStat) => { if (err) throw err; // if the file is a directory, recursively search the directory if (fileStat.isDirectory()) { searchFile(filePath, fileName); } else if (file.endsWith(fileName)) { // if the file is a match, print it console.log(filePath); } }); } }); } // start the search in the current directory searchFile('./', 'examplefile.txt');
Пожалуйста, следуйте за мной для получения дополнительной информации. Спасибо за чтение!