연습 - 파일 읽기 및 쓰기
Tailwind Traders의 Node.js를 만드는 작업을 거의 마쳤습니다. 지금까지 코드는 폴더를 읽고, 모든 .json
파일을 찾고, 폴더에 salesTotals
파일을 만듭니다totals.txt
.
이 연습에서는 저장소 합계를 추가하고 총합계를 파일에 기록 salesTotals/totals.txt
하여 프로젝트를 .json files
완료합니다.
매출 합계를 계산하는 메서드 만들기
index.js 맨 위의
require("path")
문 바로 아래에 매출 합계를 계산하는 함수를 만듭니다. 이 메서드는 반복할 수 있는 파일 경로 배열을 사용해야 합니다.async function calculateSalesTotal(salesFiles) { let salesTotal = 0; // READ FILES LOOP return salesTotal; }
해당 함수 내에서 다음 루프로 대체
// READ FILES LOOP
합니다.- (1) 배열을
salesFiles
반복합니다. - (2) 파일을 읽습니다.
- (3) 콘텐츠를 JSON으로 구문 분석합니다.
- (4) 파일의
salesTotal
값으로 변수를total
증분합니다.
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; }
- (1) 배열을
CalculateSalesTotals 메서드 호출
함수에서
main
코드를 수정하여 다음을 수행합니다.- (1) 호출 바로 위에 함수에
calculateSalesTotals
대한 호출을 추가합니다fs.writeFile
. - (2) totals.txt 파일에 변수 값을
salesTotal
쓰도록 블록을 수정fs.writeFile
합니다.
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" } ); }
- (1) 호출 바로 위에 함수에
프로그램 실행
터미널에서 프로그램을 실행합니다.
node index.js
185933.76
./salesTotals/totals.txt
파일을 열어 sales.json 및 totals.json 파일의 모든 판매액 합계(185933.76)를 확인합니다.터미널에서 프로그램을 다시 실행합니다.
node index.js
185933.76 185933.76
이제 totals.txt 파일에 두 번째 줄이 있습니다. 프로그램을 실행할 때마다 합계가 다시 계산되고 파일에 새 줄이 기록됩니다.
잘했습니다. Tailwind Traders에서 매일 밤, 모든 매장 매출을 처리하는 데 사용할 수 있는 효율적이고 강력하며 편리한 도구를 작성했습니다. 다음 섹션에서는 배운 내용을 검토하고 주의해야 할 몇 가지 팁을 살펴보겠습니다.
처리하기 어려운 부분이 있나요?
이 연습을 수행하는 동안 처리하기 어려운 부분이 있었다면 여기서 이 프로젝트의 전체 코드를 참조하세요.
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();
축하합니다! 파일을 읽고, JSON을 구문 분석하고, 총계를 파일에 기록했습니다. 프로젝트를 완료했습니다!
개발 컨테이너 정리
프로젝트를 완료한 후 개발 환경을 정리하거나 일반적인 상태로 되돌릴 수 있습니다.
GitHub Codespaces 환경을 삭제하면 계정에 대해 얻을 수 있는 코어당 무료 사용 권한을 최대화할 수 있습니다.
중요
GitHub 계정의 자격에 대한 자세한 내용은 GitHub Codespaces 월별 포함된 스토리지 및 코어 시간을 참조하세요.
GitHub Codespaces 대시보드(https://github.com/codespaces)에 로그인합니다.
MicrosoftDocs/node-essentials
GitHub 리포지토리에서 제공된 현재 실행 중인 codespace를 찾습니다.codespace에 대한 상황에 맞는 메뉴를 열고 삭제를 선택합니다.