練習 - 建立檔案和目錄

已完成

身為 Tailwind Traders 開發人員,您已在 Node.js 中建立健全的命令行應用程式,以讀取任何資料夾結構,以尋找擴展名為 .json 的檔案。 您必須讀取這些檔案以摘要檔案中的資料,然後將總額寫入稱為 salesTotals 之新目錄的新檔案中。

建立 salesTotals 目錄

  1. 在函式中 main ,將程式代碼新增至:

    • (1) 建立名為 salesTotalsDir變數,其會保存 salesTotals 目錄的路徑。
    • (2) 如果目錄不存在,請建立目錄。
    • (3) 將總計寫入 「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. 使用下列程式碼,從終端機提示執行程式。

    node index.js
    
  3. 選取 [檔案總管] 中的 [重新整理] 圖示,以查看新的檔案。 您已建立檔案,但尚未擁有總計。 下一個步驟是讀取銷售檔案、加總總額,然後將總計寫入新的 totals.txt 檔案中。 接下來,您將學習如何讀取及剖析檔案內的資料。

遇到問題了嗎?

如果您在此練習中遇到問題,以下是到目前為止的完整程式碼。

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