Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reorganizing the code sample and include final solution for the module: 'Work with files and directories in a Node.js app' #60

Merged
Merged
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"name": "Node.js",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "mcr.microsoft.com/devcontainers/javascript-node:1-18-bullseye",
"image": "mcr.microsoft.com/devcontainers/javascript-node:1-20-bullseye",
"features": {
"ghcr.io/devcontainers-contrib/features/npm-package:1": {}
},
Expand Down
9 changes: 9 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ updates:
schedule:
interval: "weekly"
open-pull-requests-limit: 10
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-patch"]

- package-ecosystem: "npm"
directory: "nodejs-files"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-patch"]
18 changes: 16 additions & 2 deletions .github/workflows/build-code.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,38 @@ jobs:
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}

- name: Module 1 - nodejs-intro
run: |
cd nodejs-intro
npm install
npm run format
npm run lint

- name: Module 2 - node-dependencies
run: |
cd node-dependencies
npm install
npm run format
npm run lint
npm test

- name: Module 3 - nodejs-debug
run: |
cd node-dependencies
npm install
npm run format
npm run lint
npm test

- name: Install Dependecies
run: |
cd nodejs-files
npm install
- name: Install Prettier
run: |
npm install -g prettier
- name: Module 4 - nodejs-files
run: |
cd nodejs-files
npm run format
npm run lint

10 changes: 10 additions & 0 deletions nodejs-files/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = auto
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
quote_type = single
25 changes: 25 additions & 0 deletions nodejs-files/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"env": {
"commonjs": true,
"es2021": true,
"node": true
},
"extends": "eslint:recommended",
"parser": "@babel/eslint-parser",
"parserOptions": {
"ecmaVersion": "latest",
"requireConfigFile": false,
"babelOptions": {
"parserOpts": {
"plugins": ["topLevelAwait"]
}
}
},
"rules": {
"no-console": "off",
"no-undef": "off",
"no-unused-vars": "off",
"no-shadow": "off",
"require-await": "error"
}
}
44 changes: 44 additions & 0 deletions nodejs-files/3-exercise-work-file-system/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// To debug in Codespaces or dev container, use
// index-unit-5.js which has the __dirname and path.join needed
// to resolve the path correctly.

const path = require('path');
const fs = require('fs').promises;

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 = [];

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, _resursively call the function `findSalesFiles` again, passing in the path to the item.
const resultsReturned = await findSalesFiles(`${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 (item.name === 'sales.json') {
results.push(`${folderName}/${item.name}`);
}
}
}
} catch (error) {
console.error('Error reading folder:', error.message);
throw error;
}

return results;
}

async function main() {
const storesFolderPath = path.join(__dirname, '..', 'stores');
const results = await findSalesFiles(storesFolderPath);
console.log(results);
}

main();
34 changes: 34 additions & 0 deletions nodejs-files/3-final-solution-exercise-work-file-system/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const path = require('path');
const fs = require("fs").promises;

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(`${folderName}/${item.name}`);
results = results.concat(resultsReturned);
} else {
if (item.name === "sales.json") {
results.push(`${folderName}/${item.name}`);
}
}
}
} catch (error) {
console.error('Error reading folder:', error.message);
throw error;
}

return results;
}

async function main() {
const storesFolderPath = path.join(__dirname, '..', 'stores');
const results = await findSalesFiles(storesFolderPath);
console.log(results);
}

main();
Original file line number Diff line number Diff line change
@@ -1,40 +1,38 @@
const fs = require("fs").promises;
const path = require("path");
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.
// (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.
// (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.
// (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));
// (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")
if (path.extname(item.name) === '.json')
results.push(`${folderName}/${item.name}`);
}
}


return results;
}

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

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

main();
main();
Original file line number Diff line number Diff line change
@@ -1,37 +1,35 @@
const fs = require("fs").promises;
const path = require("path");
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.
// (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.
// (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.
// (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));
// (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")
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");
const salesDir = path.join(__dirname, 'stores');
const salesTotalsDir = path.join(__dirname, 'salesTotals');

// create the salesTotal directory if it doesn't exist
try {
Expand All @@ -44,7 +42,7 @@ async function main() {
const salesFiles = await findSalesFiles(salesDir);

// write the total to the "totals.txt" file
await fs.writeFile(path.join(salesTotalsDir, "totals.txt"), String());
await fs.writeFile(path.join(salesTotalsDir, 'totals.txt'), String());
console.log(`Wrote sales totals to ${salesTotalsDir}`);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
const fs = require("fs").promises;
const path = require("path");
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)
const fileContents = await fs.readFile(file);

// (3) Parses the content as JSON.
const data = JSON.parse(fileContents);
Expand All @@ -22,25 +20,24 @@ async function calculateSalesTotal(salesFiles) {
}

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.
// (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.
// (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.
// (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));
// (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")
if (path.extname(item.name) === '.json')
results.push(`${folderName}/${item.name}`);
}
}
Expand All @@ -49,8 +46,8 @@ async function findSalesFiles(folderName) {
}

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 All @@ -67,11 +64,11 @@ async function main() {

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

main();
main();
Loading
Loading