연습 - 파일 및 디렉터리 만들기
Tailwind Traders 개발자는 Node.js에서 폴더 구조를 읽어 .json 확장명을 가진 파일을 찾을 수 있는 강력한 명령줄 애플리케이션을 만들었습니다. 이러한 파일을 읽어 포함된 데이터를 요약한 다음 salesTotals라는 새 디렉터리에 있는 새 파일에 합계를 써야 합니다.
salesTotals 디렉터리 만들기
함수에서
main
코드를 다음 위치에 추가합니다.- (1) salesTotals 디렉터리의 경로를 보유하는 변수를
salesTotalsDir
만듭니다. - (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}`); }
- (1) salesTotals 디렉터리의 경로를 보유하는 변수를
터미널 프롬프트에서 다음 코드를 사용하여 프로그램을 실행합니다.
node index.js
파일 탐색기에서 새로 고침 아이콘을 선택하여 새 파일을 확인합니다. 파일을 만들었지만 아직 총계가 없습니다. 다음 단계는 매출 파일을 읽고 합계를 계산한 다음, 새 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();