-
Notifications
You must be signed in to change notification settings - Fork 158
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #64 from glaucia86/GL/9-final-solution-exercise-re…
…ad-write-files chore: final solution exercise 09 from Module: 'Work with files and directories in a Node.js app'
- Loading branch information
Showing
3 changed files
with
87 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
nodejs-files/9-final-solution-exercise-read-write-files/index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file was deleted.
Oops, something went wrong.