Esercizio - Creare file e directory

Completato

Gli sviluppatori di Tailwind Traders hanno creato un'applicazione da riga di comando affidabile in Node.js in grado di leggere qualsiasi struttura di cartelle per trovare i file con estensione json. Sarà necessario leggere questi file per riepilogare i dati in essi contenuti e quindi scrivere i totali in un nuovo file in una nuova directory denominata salesTotals.

Creare la directory salesTotals

  1. main Nella funzione aggiungere il codice a:

    • (1) Creare una variabile denominata salesTotalsDir, che contiene il percorso della directory salesTotals .
    • (2) Creare la directory se non esiste già.
    • (3) Scrivere il totale nel file "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. Dal prompt dei comandi eseguire il programma con il codice seguente.

    node index.js
    
  3. Selezionare l'icona Aggiorna in Esplora file per visualizzare il nuovo file. Il file è stato creato, ma non ha ancora i totali. Il passaggio successivo consiste nel leggere i file delle vendite, sommare i totali e scrivere il totale complessivo nel nuovo file totals.txt. Nella prossima unità si vedrà come leggere e analizzare i dati all'interno dei file.

Se si riscontrano problemi

durante l'esecuzione di questo esercizio, di seguito è riportato il codice completo fino a questo punto.

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();