Latihan - Baca dan tulis ke file

Selesai

Anda hampir selesai membuat mahakarya Node.js untuk Tailwind Traders. Sejauh ini, kode Anda membaca folder apa pun, menemukan semua .json file, dan membuat totals.txt file di salesTotals folder.

Dalam latihan ini, Anda menyelesaikan proyek dengan membaca .json files, menambahkan total penyimpanan, dan menulis total keseluruhan ke salesTotals/totals.txt file.

Buat metode untuk menghitung total penjualan

  1. Di bagian atas index.js, tepat di bawah require("path") pernyataan, buat fungsi yang menghitung total penjualan. Metode ini harus mengambil array jalur file yang dapat diulangi.

    async function calculateSalesTotal(salesFiles) {
      let salesTotal = 0;
    
      // READ FILES LOOP
    
      return salesTotal;
    }
    
  2. Dalam fungsi tersebut, ganti // READ FILES LOOP dengan perulangan yang:

    • (1) Melakukan iterasi pada salesFiles array.
    • (2) Membaca file.
    • (3) Mengurai konten sebagai JSON.
    • (4) Menaikkan salesTotal variabel dengan total nilai dari file.
     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;
     }
    

Memanggil metode calculateSalesTotals

  1. main Dalam fungsi , ubah kode menjadi:

    • (1) Tambahkan panggilan ke calculateSalesTotals fungsi tepat di atas fs.writeFile panggilan.
    • (2) Ubah fs.writeFile blok untuk menulis nilai salesTotal variabel ke file totals.txt .
    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" }
      );
    }
    

Jalankan program

  1. Jalankan program dari terminal.

    node index.js
    
    185933.76
    
  2. ./salesTotals/totals.txt Buka file untuk melihat total semua penjualan dari file sales.json dan totals.json: 185933.76.

  3. Jalankan program dari terminal lagi.

    node index.js
    
    185933.76
    185933.76
    

    File totals.txt sekarang memiliki baris kedua. Setiap kali Anda menjalankan program, total ditambahkan lagi dan baris baru ditulis ke file.

Pekerjaan luar biasa! Anda telah menulis alat cerdas, kuat, dan berguna yang dapat digunakan Tailwind Traders untuk memproses semua penjualan tokonya setiap malam. Di bagian berikutnya, kami akan mengulas apa yang Anda pelajari dan beberapa tips untuk diingat.

Macet?

Jika Anda terjebak selama latihan ini, berikut adalah kode lengkap untuk proyek ini.

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

Selamat! Anda telah membaca file, mengurai JSON, dan menulis total ke file. Anda telah menyelesaikan proyek!

Membersihkan kontainer pengembangan

Setelah menyelesaikan proyek, Anda mungkin ingin membersihkan lingkungan pengembangan Anda atau mengembalikannya ke keadaan khasnya.

Menghapus lingkungan GitHub Codespaces memastikan bahwa Anda dapat memaksimalkan jumlah pemberian izin per jam inti gratis yang Anda dapatkan untuk akun Anda.

Penting

Untuk informasi selengkapnya tentang penetapan akun GitHub Anda, lihat GitHub Codespaces bulanan yang disertakan penyimpanan dan jam inti.

  1. Masuk ke dasbor GitHub Codespaces (https://github.com/codespaces).

  2. Temukan codespace yang sedang berjalan yang bersumber dari MicrosoftDocs/node-essentials repositori GitHub.

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

  3. Buka menu konteks untuk codespace dan pilih Hapus.

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