Cvičení – práce se systémem souborů
Firma Tailwind Traders má spoustu kamenných prodejen po celém světě. Každou noc se v těchto prodejnách vytvoří soubor s názvem sales.json, který obsahuje součet všech tržeb za předchozí den. Tyto soubory jsou uspořádány do složek pojmenovaných podle ID úložiště.
V tomto cvičení napíšete program Node.js, který může hledat soubory s názvem sales.json ve složce.
Otevření projektu ve vývojovém kontejneru
Spusťte proces vytvoření nového prostředí GitHub Codespace ve
main
větviMicrosoftDocs/node-essentials
úložiště GitHub.Na stránce Vytvořit kódspace zkontrolujte nastavení konfigurace codespace a pak vyberte Vytvořit nový prostor kódu.
Počkejte, až se prostor kódu spustí. Tento proces spuštění může trvat několik minut.
Otevřete nový terminál v codespace.
Ověřte, že je ve vašem prostředí nainstalovaný Node.js:
node --version
Vývojový kontejner používá verzi Node.js LTS, například
v20.5.1
. Přesná verze se může lišit.Zbývající cvičení v tomto projektu probíhají v kontextu tohoto vývojového kontejneru.
Nalezení souborů sales.json
Vaším úkolem je najít všechny soubory ve složce stores .
Rozbalte složku stores a všechny očíslované složky uvnitř.
Zahrnutí modulu fs
./nodejs-files
V podsložce vytvořte soubor index.js, který ho otevře v editoru.Do horní části souboru přidejte následující kód, který do souboru zahrne modul fs .
const fs = require("fs").promises;
Dále vytvořte
main
funkci, která je vstupním bodem pro váš kód. Poslední řádek kódu v tomto souboru vyvolá metodumain
.const fs = require("fs").promises; async function main() {} main();
Toto je typický často používaný kód CommonJS pro volání asynchronní funkce.
Zápis funkce pro vyhledání sales.json
souborů
Vytvořte novou funkci nazvanou
findSalesFiles
, která převezme parametrfolderName
.async function findSalesFiles(folderName) { // FIND SALES FILES }
findSalesFiles
Do funkce přidejte následující kód, který dokončí tyto úlohy:- (1) Přidejte pole v horní části pro uložení cest ke všem souborům prodeje, které program najde.
- (2) Přečtěte si aktuálníFolder s metodou
readdir
. - (3) Přidejte blok ke smyčce přes každou položku vrácenou
readdir
z metody pomocí asynchronnífor...of
smyčky. - (4) Přidejte
if
příkaz, který určí, zda je položka soubor nebo adresář. - (5) Pokud je položka adresářem, rekurzivně zavolejte funkci
findSalesFiles
znovu a předejte cestu k položce. - (6) Pokud se nejedná o adresář, přidejte kontrolu, abyste se ujistili, že název položky odpovídá souboru sales.json.
async function findSalesFiles(folderName) { // (1) Add an array at the top, to hold the paths to all the sales files that the program finds. let results = []; // (2) Read the currentFolder with the `readdir` method. const items = await fs.readdir(folderName, { withFileTypes: true }); // (3) Add a block to loop over each item returned from the `readdir` method using the asynchronous `for...of` loop. for (const item of items) { // (4) Add an `if` statement to determine if the item is a file or a directory. if (item.isDirectory()) { // (5) If the item is a directory, recursively call the function `findSalesFiles` again, passing in the path to the item. const resultsReturned = await findSalesFiles(`${folderName}/${item.name}`); results = results.concat(resultsReturned); } else { // (6) If it's not a directory, add a check to make sure the item name matches *sales.json*. if (item.name === "sales.json") { results.push(`${folderName}/${item.name}`); } } } return results; }
Volejte tuto novou funkci
findSaleFiles
z metodymain
. Předejte název složky stores jako umístění pro hledání souborů.async function main() { const results = await findSalesFiles("stores"); console.log(results); }
Úplná aplikace vypadá takto:
const fs = require("fs").promises; async function findSalesFiles(folderName) { // (1) Add an array at the top, to hold the paths to all the sales files that the program finds. let results = []; // (2) Read the currentFolder with the `readdir` method. const items = await fs.readdir(folderName, { withFileTypes: true }); // (3) Add a block to loop over each item returned from the `readdir` method using the asynchronous `for...of` loop. for (const item of items) { // (4) Add an `if` statement to determine if the item is a file or a directory. if (item.isDirectory()) { // (5) If the item is a directory, recursively call the function `findSalesFiles` again, passing in the path to the item. const resultsReturned = await findSalesFiles(`${folderName}/${item.name}`); results = results.concat(resultsReturned); } else { // (6) If it's not a directory, add a check to make sure the item name matches *sales.json*. if (item.name === "sales.json") { results.push(`${folderName}/${item.name}`); } } } return results; } async function main() { const results = await findSalesFiles("stores"); console.log(results); } main();
Spuštění programu
Zadáním následujícího příkazu v terminálu program spusťte.
node index.js
Program by měl zobrazit následující výstup.
[ 'stores/201/sales.json', 'stores/202/sales.json', 'stores/203/sales.json', 'stores/204/sales.json', ]
Výborně! Úspěšně jste napsali program příkazového řádku, který může procházet libovolný adresář a najít všechny soubory sales.json uvnitř.
Způsob, jakým byla v tomto příkladu zkonstruována cesta k podsložkám, je ale poněkud těžkopádný, protože vyžaduje zřetězení řetězců. Můžete také narazit na problémy u jiných operačních systémů (například ve Windows), které používají odlišné oddělovače cesty.
V další části se dozvíte, jak pomocí modulu path zkonstruovat cesty, které fungují v různých operačních systémech.
Zasekli jste se?
Pokud jste v jakémkoli bodě tohoto cvičení zasekli, zde najdete hotový kód. Odeberte veškerý kód v souboru index.js a nahraďte ho tímto řešením.
const fs = require("fs").promises;
async function findSalesFiles(folderName) {
// (1) Add an array at the top, to hold the paths to all the sales files that the program finds.
let results = [];
// (2) Read the currentFolder with the `readdir` method.
const items = await fs.readdir(folderName, { withFileTypes: true });
// (3) Add a block to loop over each item returned from the `readdir` method using the asynchronous `for...of` loop.
for (const item of items) {
// (4) Add an `if` statement to determine if the item is a file or a directory.
if (item.isDirectory()) {
// (5) If the item is a directory, recursively call the function `findSalesFiles` again, passing in the path to the item.
const resultsReturned = await findSalesFiles(`${folderName}/${item.name}`);
results = results.concat(resultsReturned);
} else {
// (6) If it's not a directory, add a check to make sure the item name matches *sales.json*.
if (item.name === "sales.json") {
results.push(`${folderName}/${item.name}`);
}
}
}
return results;
}
async function main() {
const results = await findSalesFiles("stores");
console.log(results);
}
main();