Cvičení – práce se systémem souborů

Dokončeno

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

  1. Spusťte proces vytvoření nového prostředí GitHub Codespace ve main větvi MicrosoftDocs/node-essentials úložiště GitHub.

  2. Na stránce Vytvořit kódspace zkontrolujte nastavení konfigurace codespace a pak vyberte Vytvořit nový prostor kódu.

    Screenshot of the confirmation screen before creating a new codespace.

  3. Počkejte, až se prostor kódu spustí. Tento proces spuštění může trvat několik minut.

  4. Otevřete nový terminál v codespace.

    Tip

    Pomocí hlavní nabídky můžete přejít na možnost nabídky Terminál a pak vybrat možnost Nový terminál .

    Screenshot of the codespaces menu option to open a new terminal.

  5. 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.

  6. 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ř.

Screenshot that shows the project folder structure.

Zahrnutí modulu fs

  1. ./nodejs-files V podsložce vytvořte soubor index.js, který ho otevře v editoru.

  2. Do horní části souboru přidejte následující kód, který do souboru zahrne modul fs .

    const fs = require("fs").promises;
    
  3. Dále vytvořte main funkci, která je vstupním bodem pro váš kód. Poslední řádek kódu v tomto souboru vyvolá metodu main .

    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ů

  1. Vytvořte novou funkci nazvanou findSalesFiles, která převezme parametr folderName.

    async function findSalesFiles(folderName) {
      // FIND SALES FILES
    }
    
  2. 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;
    }
    
  3. Volejte tuto novou funkci findSaleFiles z metody main. 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);
     }
    
  4. Ú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

  1. Zadáním následujícího příkazu v terminálu program spusťte.

    node index.js
    
  2. 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();