diff --git a/01-node-tutorial/answers/.gitignore b/01-node-tutorial/answers/.gitignore new file mode 100644 index 0000000000..7deb6da238 --- /dev/null +++ b/01-node-tutorial/answers/.gitignore @@ -0,0 +1,5 @@ +/node_modules + +.DS_Store + +temp.txt \ No newline at end of file diff --git a/01-node-tutorial/answers/01-intro.js b/01-node-tutorial/answers/01-intro.js new file mode 100644 index 0000000000..342dddc01f --- /dev/null +++ b/01-node-tutorial/answers/01-intro.js @@ -0,0 +1,8 @@ +const amount = 9 + +if (amount < 10) { + console.log('small number') +} else { + console.log('large number') +} + diff --git a/01-node-tutorial/answers/02-global.js b/01-node-tutorial/answers/02-global.js new file mode 100644 index 0000000000..6b29a22fec --- /dev/null +++ b/01-node-tutorial/answers/02-global.js @@ -0,0 +1,2 @@ +console.log(__dirname); +console.log(process.env.MY_VAR); diff --git a/01-node-tutorial/answers/03-modules.js b/01-node-tutorial/answers/03-modules.js new file mode 100644 index 0000000000..2816f541ec --- /dev/null +++ b/01-node-tutorial/answers/03-modules.js @@ -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]}!`) \ No newline at end of file diff --git a/01-node-tutorial/answers/04-names.js b/01-node-tutorial/answers/04-names.js new file mode 100644 index 0000000000..ede7162e5e --- /dev/null +++ b/01-node-tutorial/answers/04-names.js @@ -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 } \ No newline at end of file diff --git a/01-node-tutorial/answers/05-utils.js b/01-node-tutorial/answers/05-utils.js new file mode 100644 index 0000000000..50526abbde --- /dev/null +++ b/01-node-tutorial/answers/05-utils.js @@ -0,0 +1,5 @@ +const fullname = (first, last) => { + console.log(`Hello my full name is ${first} ${last}`) +} + +module.exports = fullname diff --git a/01-node-tutorial/answers/06-alternative-flavor.js b/01-node-tutorial/answers/06-alternative-flavor.js new file mode 100644 index 0000000000..a5d84a5de5 --- /dev/null +++ b/01-node-tutorial/answers/06-alternative-flavor.js @@ -0,0 +1,6 @@ +module.exports.favoriteFood = ['Steak', 'Cheese'] +const person = { + name: 'Jack', +} + +module.exports.singlePerson = person diff --git a/01-node-tutorial/answers/07-mind-grenade.js b/01-node-tutorial/answers/07-mind-grenade.js new file mode 100644 index 0000000000..e780dd7256 --- /dev/null +++ b/01-node-tutorial/answers/07-mind-grenade.js @@ -0,0 +1,5 @@ +function activate(name, food1, food2) { + console.log(`This was activated from another file`) +} + +activate() \ No newline at end of file diff --git a/01-node-tutorial/answers/08-os-module.js b/01-node-tutorial/answers/08-os-module.js new file mode 100644 index 0000000000..b69be937e8 --- /dev/null +++ b/01-node-tutorial/answers/08-os-module.js @@ -0,0 +1,3 @@ +const os = require("os"); + +console.log(os) \ No newline at end of file diff --git a/01-node-tutorial/answers/09-path-module.js b/01-node-tutorial/answers/09-path-module.js new file mode 100644 index 0000000000..3cf8a571f9 --- /dev/null +++ b/01-node-tutorial/answers/09-path-module.js @@ -0,0 +1,4 @@ +const path = require('path') + +const filePath = path.join('folder1', 'folder2', 'folder3', 'file.txt') +console.log(filePath) \ No newline at end of file diff --git a/01-node-tutorial/answers/10-fs-sync.js b/01-node-tutorial/answers/10-fs-sync.js new file mode 100644 index 0000000000..7644b5c484 --- /dev/null +++ b/01-node-tutorial/answers/10-fs-sync.js @@ -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) \ No newline at end of file diff --git a/01-node-tutorial/answers/11-fs-async.js b/01-node-tutorial/answers/11-fs-async.js new file mode 100644 index 0000000000..3aacdb4fd7 --- /dev/null +++ b/01-node-tutorial/answers/11-fs-async.js @@ -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"); \ No newline at end of file diff --git a/01-node-tutorial/answers/12-http.js b/01-node-tutorial/answers/12-http.js new file mode 100644 index 0000000000..32d974e0e0 --- /dev/null +++ b/01-node-tutorial/answers/12-http.js @@ -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(` +
PAGE YOU ARE LOOKING FOR DOESN'T EXIST
+ back home + `) + } +}) + +server.listen(3000) +console.log('Server is listening on port 3000...') \ No newline at end of file diff --git a/01-node-tutorial/answers/16-streams.js b/01-node-tutorial/answers/16-streams.js new file mode 100644 index 0000000000..b3161e7c4b --- /dev/null +++ b/01-node-tutorial/answers/16-streams.js @@ -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); +}); diff --git a/01-node-tutorial/answers/customEmitter.js b/01-node-tutorial/answers/customEmitter.js new file mode 100644 index 0000000000..7edd273233 --- /dev/null +++ b/01-node-tutorial/answers/customEmitter.js @@ -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); diff --git a/01-node-tutorial/answers/prompter.js b/01-node-tutorial/answers/prompter.js index 38e93d8311..ff8859a29c 100644 --- a/01-node-tutorial/answers/prompter.js +++ b/01-node-tutorial/answers/prompter.js @@ -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 ` -${item}
- +${message}
+Attempts: ${attempts}
+ + `; }; @@ -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: "/", }); @@ -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."); \ No newline at end of file diff --git a/01-node-tutorial/answers/writeWithPromisesThen.js b/01-node-tutorial/answers/writeWithPromisesThen.js new file mode 100644 index 0000000000..4ae09935a5 --- /dev/null +++ b/01-node-tutorial/answers/writeWithPromisesThen.js @@ -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); + }); diff --git a/01-node-tutorial/answers/writeWithpromisesAwait.js b/01-node-tutorial/answers/writeWithpromisesAwait.js new file mode 100644 index 0000000000..5ad0c9610d --- /dev/null +++ b/01-node-tutorial/answers/writeWithpromisesAwait.js @@ -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(); \ No newline at end of file diff --git a/02-express-tutorial/app.js b/02-express-tutorial/app.js index ce296a6ee3..400bc3e618 100644 --- a/02-express-tutorial/app.js +++ b/02-express-tutorial/app.js @@ -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}...`); +}); diff --git a/02-express-tutorial/controllers/people.js b/02-express-tutorial/controllers/people.js new file mode 100644 index 0000000000..c3696ef1ef --- /dev/null +++ b/02-express-tutorial/controllers/people.js @@ -0,0 +1,22 @@ +const { people } = require("../data"); + +const getPeople = (req, res) => { + return res.status(200).json(people); +}; + +const addPerson = (req, res) => { + const { name } = req.body; + + if (!name) { + return res + .status(400) + .json({ success: false, message: "Please provide a name" }); +} + + const newPerson = { id: people.length + 1, name }; + people.push(newPerson); + + return res.status(201).json({ success: true, data: newPerson }); +}; + +module.exports = { getPeople, addPerson }; diff --git a/02-express-tutorial/public/index.html b/02-express-tutorial/public/index.html new file mode 100644 index 0000000000..45f0b73d41 --- /dev/null +++ b/02-express-tutorial/public/index.html @@ -0,0 +1,40 @@ + + + + + +