Skip to content

Commit

Permalink
Merge pull request #64 from glaucia86/GL/9-final-solution-exercise-re…
Browse files Browse the repository at this point in the history
…ad-write-files

chore: final solution exercise 09 from Module: 'Work with files and directories in a Node.js app'
  • Loading branch information
glaucia86 authored Feb 6, 2024
2 parents 698bf52 + 189e755 commit 1b7bcbf
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,37 @@ 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 });
try {
// (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}`);
}
}

// (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, _resursively 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;
}
} catch (error) {
console.error('Error reading folder:', error.message);
throw error;
}

return results;
}

async function main() {
const salesDir = path.join(__dirname, 'stores');
const salesTotalsDir = path.join(__dirname, 'salesTotals');
const salesDir = path.join(__dirname, '..', 'stores');
const salesTotalsDir = path.join(__dirname, '..', 'salesTotals');

// create the salesTotal directory if it doesn't exist
try {
Expand Down
62 changes: 62 additions & 0 deletions nodejs-files/9-final-solution-exercise-read-write-files/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const fs = require('fs').promises;
const path = require('path');

async function calculateSalesTotal(salesFiles) {
let salesTotal = 0;

for (file of salesFiles) {
const fileContents = await fs.readFile(file);
const data = JSON.parse(fileContents);
salesTotal += data.total;
}
return salesTotal;
}

async function findSalesFiles(folderName) {
let results = [];

try {
const items = await fs.readdir(folderName, { withFileTypes: true });
for (const item of items) {
if (item.isDirectory()) {
const resultsReturned = await findSalesFiles(
path.join(folderName, item.name),
);
results = results.concat(resultsReturned);
} else {
if (path.extname(item.name) === '.json') {
results.push(`${folderName}/${item.name}`);
}
}

return results;
}
} catch (error) {
console.error('Error reading folder:', error.message);
throw error;
}
}

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

const salesTotal = await calculateSalesTotal(salesFiles);

await fs.writeFile(
path.join(salesTotalsDir, 'totals.txt'),
`${salesTotal}\r\n`,
{ flag: 'a' },
);
console.log(`Wrote sales totals to ${salesTotalsDir}`);
}

main();
7 changes: 0 additions & 7 deletions nodejs-files/index-unit-4.js

This file was deleted.

0 comments on commit 1b7bcbf

Please sign in to comment.