Skip to content
Open

Week7 #483

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions 01-node-tutorial/answers/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/node_modules

.DS_Store

temp.txt
8 changes: 8 additions & 0 deletions 01-node-tutorial/answers/01-intro.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const amount = 9

if (amount < 10) {
console.log('small number')
} else {
console.log('large number')
}

2 changes: 2 additions & 0 deletions 01-node-tutorial/answers/02-global.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
console.log(__dirname);
console.log(process.env.MY_VAR);
7 changes: 7 additions & 0 deletions 01-node-tutorial/answers/03-modules.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const names = require("./04-names.js");
const fullname = require("./05-utils.js")
const alt = require("./06-alternative-flavor.js")
const activate = require("./07-mind-grenade.js")

fullname(names.carl, names.carl_lastname)
console.log(`Hello my name is ${alt.singlePerson.name} my favorite foods are ${alt.favoriteFood[0]} and ${alt.favoriteFood[1]}!`)
6 changes: 6 additions & 0 deletions 01-node-tutorial/answers/04-names.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const carl = 'Carl'
const carl_lastname = 'Balansag'
const random_name = 'Jake'
const random_name_lastname = 'Smith'

module.exports = { carl, carl_lastname, random_name, random_name_lastname }
5 changes: 5 additions & 0 deletions 01-node-tutorial/answers/05-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const fullname = (first, last) => {
console.log(`Hello my full name is ${first} ${last}`)
}

module.exports = fullname
6 changes: 6 additions & 0 deletions 01-node-tutorial/answers/06-alternative-flavor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports.favoriteFood = ['Steak', 'Cheese']
const person = {
name: 'Jack',
}

module.exports.singlePerson = person
5 changes: 5 additions & 0 deletions 01-node-tutorial/answers/07-mind-grenade.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function activate(name, food1, food2) {
console.log(`This was activated from another file`)
}

activate()
3 changes: 3 additions & 0 deletions 01-node-tutorial/answers/08-os-module.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const os = require("os");

console.log(os)
4 changes: 4 additions & 0 deletions 01-node-tutorial/answers/09-path-module.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const path = require('path')

const filePath = path.join('folder1', 'folder2', 'folder3', 'file.txt')
console.log(filePath)
15 changes: 15 additions & 0 deletions 01-node-tutorial/answers/10-fs-sync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { writeFileSync, readFileSync } = require('fs')

//Creates the file (or overwrites if it exists)
writeFileSync('./temporary/fileA.txt', 'This is line 1\n')

//Append flag adds to the file
writeFileSync('./temporary/fileA.txt', 'This is line 2\n', { flag: 'a' })

//Apend flag adds to the file
writeFileSync('./temporary/fileA.txt', 'This is line 3\n', { flag: 'a' })

//Read the file
const content = readFileSync('./temporary/fileA.txt', 'utf8')

console.log(content)
29 changes: 29 additions & 0 deletions 01-node-tutorial/answers/11-fs-async.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const { writeFile } = require("fs");
console.log("at start");
writeFile("./temporary/fileB.txt", "This is line 1\n", (err, result) => {
console.log("at point 1");
if (err) {
console.log("This error happened: ", err);
} else {
//Write line 2 inside this callback
writeFile("./temporary/fileB.txt", "This is line 2\n", { flag: "a" }, (err, result) => {
console.log("at point 2");
if (err) {
console.log("This error happened: ", err);
} else {
//Write line 3 inside this callback
writeFile("./temporary/fileB.txt", "This is line 3\n", { flag: "a" }, (err, result) => {
console.log("at point 3");
if (err) {
console.log("This error happened: ", err);
} else {
//Everything worked write completed
console.log("File writing complete!");
}
});
}
});
}
});

console.log("at end");
18 changes: 18 additions & 0 deletions 01-node-tutorial/answers/12-http.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const http = require('http')

const server = http.createServer((req, res) => {
if (req.url === '/') {
res.end('This is the the home page')
} else if (req.url === '/about') {
res.end('This is the about page')
} else {
res.end(`
<h1>ERROR!</h1>
<p>PAGE YOU ARE LOOKING FOR DOESN'T EXIST</p>
<a href="/">back home</a>
`)
}
})

server.listen(3000)
console.log('Server is listening on port 3000...')
21 changes: 21 additions & 0 deletions 01-node-tutorial/answers/16-streams.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const { createReadStream } = require('fs');

const stream = createReadStream('../content/big.txt', {
encoding: 'utf8',
highWaterMark: 200
});

let counter = 0;

stream.on('data', (result) => {
counter++;
console.log(`Chunk ${counter}:`, result);
});

stream.on('end', () => {
console.log(`\nStream ended. Total chunks received: ${counter}`);
});

stream.on('error', (error) => {
console.error('Error reading stream:', error);
});
22 changes: 22 additions & 0 deletions 01-node-tutorial/answers/customEmitter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const EventEmitter = require("events");

// Create an emitter
const emitter = new EventEmitter();

// Set up event handlers
emitter.on("greeting", (name) => {
console.log(`Hello, ${name}!`);
});

emitter.on("timer", (msg) => {
console.log(msg);
});

// Emit some events
emitter.emit("greeting", "Tom");
emitter.emit("greeting", "Bob");

// Set up a timer that emits events every 2 seconds
setInterval(() => {
emitter.emit("timer", "Timer event triggered");
}, 2000);
60 changes: 45 additions & 15 deletions 01-node-tutorial/answers/prompter.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,24 @@ const getBody = (req, callback) => {
});
};

// here, you could declare one or more variables to store what comes back from the form.
let item = "Enter something below.";
//Generate a random secret number between 1 and 100
let secretNumber = Math.floor(Math.random() * 100) + 1;
let message = "Guess the number between 1 and 100.";
let attempts = 0;

// here, you can change the form below to modify the input fields and what is displayed.
// This is just ordinary html with string interpolation.
const form = () => {
return `
<body>
<p>${item}</p>
<form method="POST">
<input name="item"></input>
<button type="submit">Submit</button>
</form>
<h1>Number Guessing Game</h1>
<p>${message}</p>
<p>Attempts: ${attempts}</p>
<form method="POST">
<input name="guess" type="number" min="1" max="100" placeholder="Enter your guess"></input>
<button type="submit">Guess</button>
</form>
<form method="POST">
<button name="reset" value="true" type="submit">New Game</button>
</form>
</body>
`;
};
Expand All @@ -43,13 +48,35 @@ const server = http.createServer((req, res) => {
if (req.method === "POST") {
getBody(req, (body) => {
console.log("The body of the post is ", body);
// here, you can add your own logic
if (body["item"]) {
item = body["item"];

// Check if user wants to reset the game
if (body["reset"]) {
secretNumber = Math.floor(Math.random() * 100) + 1;
message = "New game started! Guess the number between 1 and 100.";
attempts = 0;
console.log(`New secret number generated: ${secretNumber}`);
}
// Process the guess
else if (body["guess"]) {
const guess = parseInt(body["guess"]);
attempts++;

console.log(`Player guessed: ${guess}, Secret number: ${secretNumber}, Attempts: ${attempts}`);

if (isNaN(guess)) {
message = "Please enter a valid number!";
} else if (guess === secretNumber) {
message = `Congratulations! You guessed it in ${attempts} attempts! The number was ${secretNumber}.`;
console.log(`Player won in ${attempts} attempts!`);
} else if (guess < secretNumber) {
message = `Too low! Try again. (Attempt ${attempts})`;
} else {
message = `Too high! Try again. (Attempt ${attempts})`;
}
} else {
item = "Nothing was entered.";
message = "Please enter a guess!";
}
// Your code changes would end here

res.writeHead(303, {
Location: "/",
});
Expand All @@ -60,5 +87,8 @@ const server = http.createServer((req, res) => {
}
});

server.on("request", (req) => {
console.log("event received: ", req.method, req.url);
});
server.listen(3000);
console.log("The server is listening on port 3000.");
console.log("The server is listening on port 3000.");
18 changes: 18 additions & 0 deletions 01-node-tutorial/answers/writeWithPromisesThen.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { writeFile, readFile } = require("fs").promises;

writeFile('./temporary/temp.txt', 'This is line 1\n')
.then(() => {
return writeFile('./temporary/temp.txt', 'This is line 2\n', { flag: 'a' });
})
.then(() => {
return writeFile('./temporary/temp.txt', 'This is line 3\n', { flag: 'a' });
})
.then(() => {
return readFile('./temporary/temp.txt', 'utf8');
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log("An error occurred: ", error);
});
28 changes: 28 additions & 0 deletions 01-node-tutorial/answers/writeWithpromisesAwait.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { writeFile, readFile } = require("fs").promises;

async function writer() {
try {
await writeFile('./temporary/temp.txt', 'This is line 1\n');
await writeFile('./temporary/temp.txt', 'This is line 2\n', { flag: 'a' });
await writeFile('./temporary/temp.txt', 'This is line 3\n', { flag: 'a' });
console.log('File written successfully');
} catch (error) {
console.error('Error writing file:', error);
}
}

async function reader() {
try {
const content = await readFile('./temporary/temp.txt', 'utf8');
console.log(content);
} catch (error) {
console.error('Error reading file:', error);
}
}

async function readWrite() {
await writer();
await reader();
}

readWrite();
81 changes: 81 additions & 0 deletions 02-express-tutorial/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,82 @@
console.log('Express Tutorial')
const express = require('express');
const { products } = require("./data");
const peopleRouter = require("./routes/people");
const app = express();

//Middleware

const logger = (req, res, next) => {
const method = req.method
const url = req.url
const time = new Date().getFullYear()
console.log(method, url, time)
next()
}

app.use(logger);
app.use(express.static('./public'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

//ROUTES
app.get('/api/v1/test', (req, res) => {
res.json({ message: "It worked!" });
});

app.get('/api/v1/products/:productID', (req, res) => {
const idToFind = parseInt(req.params.productID);
const product = products.find((p) => p.id === idToFind);

if (!product) { return res.status(404).json({ message: "That product was not found." });}

res.json(product);
});

app.get('/api/v1/query', (req, res) => {
const { search, limit, maxPrice } = req.query;
let result = [...products];

//filter by search when the name starts with ""
if (search) {
result = result.filter((input) =>
input.name.toLowerCase().startsWith(search.toLowerCase())
);
}

//filter by the max price
if (maxPrice) {
const maxPriceNum = parseFloat(maxPrice);
if (!isNaN(maxPriceNum)) {
result = result.filter((input) => input.price <= maxPriceNum);
}
}

//limit results
if (limit) {
const limitNum = parseInt(limit);
if (!isNaN(limitNum) && limitNum > 0) {
result = result.slice(0, limitNum);
}
}

res.json(result);
});

app.get('/api/v1/products', (req, res) => {
res.json(products);
});

app.use("/api/v1/people", peopleRouter);


//Handle Errors
app.all('*', (req, res) => {
res.status(404).send('Page not found');
});


const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server on port ${PORT}...`);
});
Loading