Oefening: Lezen en schrijven naar bestanden

Voltooid

U bent bijna klaar met het maken van een uitstekend Node.js-project voor Tailwind Traders. Tot nu toe leest uw code elke map, vindt u alle .json bestanden en maakt u een totals.txt bestand in de salesTotals map.

In deze oefening voltooit u het project door de totalen van de .json fileswinkel op te tellen en het eindtotaal naar het salesTotals/totals.txt bestand te schrijven.

Een methode maken voor het berekenen van de totale verkoop

  1. Maak boven aan index.js, net onder de require("path") instructie, een functie waarmee het verkooptotaal wordt berekend. Bij deze methode moet rekening worden gehouden met de matrix van bestandspaden die kunnen worden herhaald.

    async function calculateSalesTotal(salesFiles) {
      let salesTotal = 0;
    
      // READ FILES LOOP
    
      return salesTotal;
    }
    
  2. Vervang binnen die functie door // READ FILES LOOP een lus die:

    • (1) Herhaalt de salesFiles matrix.
    • (2) Leest het bestand.
    • (3) Parseert de inhoud als JSON.
    • (4) Hiermee wordt de salesTotal variabele verhoogd met de total waarde uit het bestand.
     async function calculateSalesTotal(salesFiles) {
    
       // Final sales total
       let salesTotal = 0;
    
       // (1) Tterates over the `salesFiles` array.
       for (file of salesFiles) {
    
         // (2) Reads the file.
         const fileContents = await fs.readFile(file)
    
         // (3) Parses the content as JSON.
         const data = JSON.parse(fileContents);
    
         // (4) Increments the `salesTotal` variable with the `total` value from the file.
         salesTotal += data.total;
       }
       return salesTotal;
     }
    

De calculateSalesTotals-methode aanroepen

  1. Wijzig de code in de main functie in:

    • (1) Voeg een aanroep toe aan de calculateSalesTotals functie net boven de fs.writeFile aanroep.
    • (2) Wijzig het fs.writeFile blok om de waarde van de salesTotal variabele naar het bestand totals.txt te schrijven.
    async function main() {
      const salesDir = path.join(__dirname, "stores");
      const salesTotalsDir = path.join(__dirname, "salesTotals");
    
      try {
        await fs.mkdir(salesTotalsDir);
      } catch {
        console.log(`${salesTotalsDir} already exists.`);
      }
    
      const salesFiles = await findSalesFiles(salesDir);
    
      // (1) Add a call to the `calculateSalesTotals` function just above the `fs.writeFile` call.
      const salesTotal = await calculateSalesTotal(salesFiles);
    
      // (2) Modify the `fs.writeFile` block to write the value of the `salesTotal` variable to the *totals.txt* file.
      await fs.writeFile(
        path.join(salesTotalsDir, "totals.txt"),
        `${salesTotal}\r\n`,
        { flag: "a" }
      );
    }
    

Het programma uitvoeren

  1. Voer het programma uit vanaf de terminal.

    node index.js
    
    185933.76
    
  2. Open het ./salesTotals/totals.txt bestand om het totaal van alle verkopen uit de bestanden sales.json en totals.json te zien: 185933.76.

  3. Voer het programma nogmaals uit vanaf de terminal.

    node index.js
    
    185933.76
    185933.76
    

    Het bestand totals.txt heeft nu een tweede regel. Telkens wanneer u het programma uitvoert, worden de totalen opnieuw toegevoegd en wordt een nieuwe regel naar het bestand geschreven.

Perfect! U hebt een slim, robuust en handig hulpprogramma geschreven waarmee Tailwind Traders elke avond de verkoop van alle winkels kan verwerken. In de volgende sectie gaan we na wat u hebt geleerd en krijgt u een aantal tips om te onthouden.

Vastgelopen?

Als u tijdens deze oefening niet meer weet hoe u verder moet, vindt u hier de volledige code voor dit project.

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

async function calculateSalesTotal(salesFiles) {
  
  // Final sales total
  let salesTotal = 0;
  
  // (1) Tterates over the `salesFiles` array.
  for (file of salesFiles) {
    
    // (2) Reads the file.
    const fileContents = await fs.readFile(file)

    // (3) Parses the content as JSON.
    const data = JSON.parse(fileContents);

    // (4) Increments the `salesTotal` variable with the `total` value from the file.
    salesTotal += data.total;
  }
  return salesTotal;
}

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");
  const salesTotalsDir = path.join(__dirname, "salesTotals");

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

  // find paths to all the sales files
  const salesFiles = await findSalesFiles(salesDir);

  // read through each sales file to calculate the sales total
  const salesTotal = await calculateSalesTotal(salesFiles);

  // write the total to the "totals.json" file
  await fs.writeFile(
    path.join(salesTotalsDir, "totals.txt"),
    `${salesTotal}\r\n`,
    { flag: "a" }
  );
  console.log(`Wrote sales totals to ${salesTotalsDir}`);
}

main();

Gefeliciteerd. U hebt de bestanden gelezen, de JSON geparseerd en het totaal naar een bestand geschreven. U hebt het project voltooid.

Ontwikkelcontainer opschonen

Nadat u het project hebt voltooid, kunt u uw ontwikkelomgeving opschonen of teruggaan naar de typische status.

Als u de GitHub Codespaces-omgeving verwijdert, zorgt u ervoor dat u de hoeveelheid gratis rechten per kernuren kunt maximaliseren die u voor uw account krijgt.

Belangrijk

Zie GitHub Codespaces maandelijks inbegrepen opslag- en kernuren voor meer informatie over de rechten van uw GitHub-account.

  1. Meld u aan bij het GitHub Codespaces-dashboard (https://github.com/codespaces).

  2. Zoek de codespaces die momenteel worden uitgevoerd vanuit de MicrosoftDocs/node-essentials GitHub-opslagplaats.

    Screenshot of all the running codespaces including their status and templates.

  3. Open het contextmenu voor de coderuimte en selecteer Verwijderen.

    Screenshot of the context menu for a single codespace with the delete option highlighted.