연습 - 경로 작업

완료됨

Tailwind Traders의 개발자는 Node.js 경로 모듈 및 __dirname 전역 변수를 사용하여 프로그램을 향상하려고 합니다. 이렇게 하면 프로그램이 실행되는 위치에 관계없이 .json 파일을 동적으로 찾아서 처리할 수 있습니다.

path 모듈 포함

기존 index.js 파일의 맨 위에 경로 모듈을 포함합니다.

const path = require("path");

현재 디렉터리 사용

현재 index.js 코드에서 stores 폴더의 정적 위치를 전달하고 있습니다. 정적 폴더 이름을 전달하는 대신 __dirname 값을 사용하도록 해당 코드를 변경하겠습니다.

  1. main 메서드에서 __dirname 상수를 사용하여 stores 디렉터리의 경로를 저장할 변수를 만듭니다.

    async function main() {
      const salesDir = path.join(__dirname, "stores");
    
      const salesFiles = await findSalesFiles(salesDir);
      console.log(salesFiles);
    }
    
  2. 명령줄에서 프로그램을 실행합니다.

    node index.js
    

    __dirname 상수는 현재 위치에 대한 전체 경로를 반환하므로 현재 파일에 대해 나열된 경로는 전체 시스템 경로입니다.

    [
       '/workspaces/node-essentials/nodejs-files/stores/201/sales.json',
       '/workspaces/node-essentials/nodejs-files/stores/202/sales.json',
       '/workspaces/node-essentials/nodejs-files/stores/203/sales.json',
       '/workspaces/node-essentials/nodejs-files/stores/204/sales.json'
    ]
    

조인 경로

폴더 이름을 연결하여 검색할 새 경로를 작성하는 대신 path.join 메서드를 사용하도록 코드를 변경하겠습니다. 그러면 코드가 여러 운영 체제에서 작동합니다.

  1. path.join을 사용하도록 findFiles 메서드를 변경합니다.

    // previous code - with string concatentation
    const resultsReturned = await findSalesFiles(`${folderName}/${item.name}`);
    
    // current code - with path.join
    const resultsReturned = await findSalesFiles(path.join(folderName,item.name));
    
  2. 명령줄에서 프로그램을 실행합니다.

    node index.js
    

    출력은 이전 단계와 동일하지만 이제 프로그램에서 문자열을 연결하는 대신 path.join을 사용하기 때문에 더욱 강력해집니다.

모든 .json 파일 찾기

프로그램에서 sales.json 파일만 찾는 대신 확장명이 .json인 파일을 모두 검색해야 합니다. 이렇게 하려면 path.extname 메서드를 사용하여 파일 이름 확장명을 확인합니다.

  1. 터미널에서 다음 명령을 실행하여 stores/201/sales.json 파일의 이름을 stores/sales/totals.json으로 바꿉니다.

    mv stores/201/sales.json stores/201/totals.json
    
  2. 함수에서 findSalesFiles 문을 파일 이름 확장명만 검사 변경 if 합니다.

    if (path.extname(item.name) === ".json") {
      results.push(`${folderName}/${item.name}`);
    }
    
  3. 명령줄에서 프로그램을 실행합니다.

    node index.js
    

    이제 매장 ID 디렉터리에 있는 .json 파일이 모두 출력에 표시됩니다.

    [
       '/home/username/node-essentials/nodejs-files/stores/201/totals.json',
       '/home/username/node-essentials/nodejs-files/stores/202/sales.json',
       '/home/username/node-essentials/nodejs-files/stores/203/sales.json',
       '/home/username/node-essentials/nodejs-files/stores/204/sales.json'
    ]
    

잘했습니다. path 모듈과 __dirname 상수를 사용하여 프로그램을 훨씬 더 강력하게 만들었습니다. 다음 섹션에서는 디렉터리를 만들고 위치 간에 파일을 이동하는 방법을 알아봅니다.

처리하기 어려운 부분이 있나요?

이 연습을 수행하는 동안 처리하기 어려운 부분이 있었다면 여기서 완성된 코드를 참조하세요. index.js의 모든 내용을 제거하고 이 솔루션으로 바꿉니다.

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` method 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");

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

main();