Ejercicio: Crear archivos y directorios

Completado

Como desarrollador de Tailwind Traders, ha creado una aplicación de línea de comandos sólida en Node.js que puede leer cualquier estructura de carpetas para encontrar archivos con la extensión .json. Deberá leer esos archivos para resumir los datos que contengan y, tras ello, escribir los totales en un archivo nuevo, dentro de un directorio nuevo llamado salesTotals.

Creación del directorio salesTotals

  1. En la función main, agregue código para:

    • (1) Crear una variable denominada salesTotalsDir, que contenga la ruta de acceso del directorio salesTotals.
    • (2) Crear el directorio si aún no existe.
    • (3) Escribir el total en el archivo "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. Desde el símbolo del sistema de terminal ejecute el programa con el código siguiente.

    node index.js
    
  3. Seleccione el icono Actualizar en el explorador Files para ver el nuevo archivo. Ha creado el archivo, pero aún no tiene los totales. El siguiente paso es leer los archivos de ventas, sumar los totales y escribir el total general en el nuevo archivo totals.txt. Después, obtendrá información sobre cómo leer y analizar los datos incluidos en los archivos.

¿Se ha bloqueado?

Si se ha bloqueado durante este ejercicio, este es el código completo hasta el momento.

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