Övning – Skapa filer och kataloger

Slutförd

Som Tailwind Traders-utvecklare har du skapat ett robust kommandoradsprogram i Node.js som kan läsa valfri mappstruktur för att hitta filer med ett .json-tillägg. Du måste läsa dessa filer för att sammanfatta data i dem och sedan skriva summorna till en ny fil i en ny katalog med namnet salesTotals.

Skapa katalogen salesTotals

  1. I funktionen main lägger du till kod i:

    • (1) Skapa en variabel med namnet salesTotalsDir, som innehåller sökvägen till katalogen salesTotals .
    • (2) Skapa katalogen om den inte redan finns.
    • (3) Skriv summan till filen "totals.txt".
     async function main() {
       const salesDir = path.join(__dirname, "stores");
    
       // (1) Create a variable called `salesTotalsDir`, which holds the path of the *salesTotals* directory.
       const salesTotalsDir = path.join(__dirname, "salesTotals");
    
       try {
         // (2) Create the directory if it doesn't already exist.
         await fs.mkdir(salesTotalsDir);
       } catch {
         console.log(`${salesTotalsDir} already exists.`);
       }
    
       // Calculate sales totals
       const salesFiles = await findSalesFiles(salesDir);
    
       // (3) Write the total to the "totals.txt" file with empty string `String()`
       await fs.writeFile(path.join(salesTotalsDir, "totals.txt"), String());
       console.log(`Wrote sales totals to ${salesTotalsDir}`);
     }
    
  2. Kör programmet med följande kod från terminalprompten.

    node index.js
    
  3. Välj ikonen Uppdatera i Utforskaren för att se den nya filen. Du har skapat filen men den har inte summorna ännu. Nästa steg är att läsa försäljningsfilerna, lägga till summorna och skriva totalsumman till den nya filen totalsummor.txt . Härnäst lär du dig att läsa och parsa data i filer.

Har du fastnat?

Om du har fastnat i den här övningen finns den fullständiga koden som vi skapat hittills för projektet här.

const fs = require("fs").promises;
const path = require("path");

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` function 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(path.join(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 (path.extname(item.name) === ".json")
        results.push(`${folderName}/${item.name}`);
    }
  }


  return results;
}

async function main() {
  const salesDir = path.join(__dirname, "stores");

  // (1) Create a variable called `salesTotalsDir`, which holds the path of the *salesTotals* directory.
  const salesTotalsDir = path.join(__dirname, "salesTotals");

  try {
    // (2) Create the directory if it doesn't already exist.
    await fs.mkdir(salesTotalsDir);
  } catch {
    console.log(`${salesTotalsDir} already exists.`);
  }

  // Calculate sales totals
  const salesFiles = await findSalesFiles(salesDir);

  // (3) Write the total to the "totals.txt" file with empty string `String()`
  await fs.writeFile(path.join(salesTotalsDir, "totals.txt"), String());
  console.log(`Wrote sales totals to ${salesTotalsDir}`);
}

main();