├── .github └── FUNDING.yml ├── .idea ├── .gitignore ├── NodeJS-Projects.iml ├── discord.xml ├── modules.xml └── vcs.xml ├── Age Calculator ├── app.js ├── date.js ├── package-lock.json ├── package.json └── views │ ├── age.ejs │ └── home.ejs ├── AutoCreateGithub.js ├── Build_directory_of_books ├── CONTRIBUTING.md └── build_books.js ├── CV online ├── README.md ├── app.js ├── index.html └── style.css ├── DedeJaelani.js ├── DedeJaelani2.js ├── DzikriMuhammad.js ├── Eilaluth.js ├── Esavwede_Ogagaoghene ├── .gitignore ├── BackendProjects │ └── list.md ├── Events │ └── emitter.js ├── FileManagement │ ├── hello.txt │ └── index.js ├── Modules │ ├── README.js │ ├── app.js │ └── checkDriver.js ├── NodeJsScheduling │ └── app.js ├── app.js ├── package-lock.json └── package.json ├── Hello_world_example.js ├── LICENSE.md ├── LdapHelper.js ├── Mybest-bot-auto-main ├── LICENSE ├── README.md ├── ascii.txt └── index.js ├── Pemula ├── README.md ├── Rashid ├── Tes └── index.js ├── Reqruitment Tests Example ├── bloodRelation.js ├── goodPassword.js ├── package-lock.json └── package.json ├── Result Management System ├── app.js ├── controllers │ ├── studentController.js │ └── teacherController.js ├── models │ └── student.js ├── package-lock.json ├── package.json ├── public │ └── style.css ├── routes │ ├── studentRoutes.js │ └── teacherRoutes.js └── views │ ├── 404.ejs │ ├── index.ejs │ ├── layouts │ └── layout.ejs │ ├── partials │ └── navbar.ejs │ ├── student │ ├── login.ejs │ └── view.ejs │ └── teacher │ ├── addstudent.ejs │ ├── edit.ejs │ ├── option.ejs │ ├── teacherLogin.ejs │ └── viewall.ejs ├── Sastra.js ├── SimpleApiCostumizeable.js ├── TechifyAU.js ├── Tic-Tac-Toe ├── board.js ├── client.html ├── connection.js ├── game.js └── server.js ├── TiktokDownloaderNoWM_ByMRHRTZ.js ├── UserEndpoints_shyam640 ├── config │ └── dev.env ├── package-lock.json ├── package.json └── src │ ├── db │ └── mongoose.js │ ├── index.js │ ├── middleware │ └── authmiddleware.js │ └── model │ └── usermodel.js ├── absensi_isal.js ├── ads.js ├── agetta.js ├── alarm.js ├── asnjry.js ├── autoCreateMSEdu.js ├── bissmillah.js ├── breakout ├── index.html ├── index.js └── styles.css ├── calculator.js ├── capitalFirstLetter.js ├── change img to base64 ├── index.js └── package.json ├── check-vowel-char.js ├── chossopian.js ├── cnn.js ├── cola.js ├── connectwallet.js ├── contact-app ├── .gitignore ├── contacts.js ├── data │ └── contacts.json ├── index.js ├── package-lock.json └── package.json ├── convert-img-to-base64.js ├── cors_by_yasas.js ├── create_server.js ├── dimmn-dolanan suit jepang.js ├── e-commerce_scrapper └── index.js ├── ecommerce-store ├── .gitignore ├── README.md ├── backend │ ├── app.js │ ├── config │ │ ├── keys.js │ │ ├── keys_dev.js │ │ └── keys_prod.js │ ├── db.js │ ├── model │ │ ├── CatModal.js │ │ ├── ProductModal.js │ │ └── User.js │ ├── package-lock.json │ ├── package.json │ ├── routes │ │ ├── auth.js │ │ ├── cat.js │ │ ├── product.js │ │ └── users.js │ └── validation.js └── frontend │ ├── .gitignore │ ├── README.md │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt │ └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── Private-route.jsx │ ├── assets │ ├── crown.svg │ └── shopping-bag.svg │ ├── components │ ├── cart-dropdown │ │ ├── cart-dropdown.component.jsx │ │ └── cart-dropdown.styles.scss │ ├── cart-icon │ │ ├── cart-icon.component.jsx │ │ └── cart-icon.styles.scss │ ├── cart-item │ │ ├── cart-item.component.jsx │ │ └── cart-item.styles.scss │ ├── category │ │ ├── cat_data.js │ │ ├── category.component.jsx │ │ └── category.styles.scss │ ├── checkout-item │ │ ├── checkout-item.component.jsx │ │ └── checkout-item.styles.scss │ ├── custom-button │ │ ├── custom-button.component.jsx │ │ └── custom-button.styles.scss │ ├── directory-item │ │ ├── directoryItem.component.jsx │ │ └── directoryItem.styles.scss │ ├── directory │ │ ├── directory-data.js │ │ ├── directory.component.jsx │ │ └── directory.styles.scss │ ├── footer │ │ ├── footer.component.jsx │ │ └── footer.styles.scss │ ├── form-input │ │ ├── form-input.component.jsx │ │ └── form-input.styles.scss │ ├── navLinks │ │ └── navLink.component.jsx │ ├── navigation │ │ ├── mainNavigation.component.jsx │ │ └── mainNavigation.styles.scss │ ├── shop-item-card │ │ ├── shopItemCard.component.jsx │ │ └── shopItemCard.styles.scss │ ├── shop-items │ │ ├── shop-items.component.jsx │ │ ├── shop-items.styles.scss │ │ └── shop.data.js.js │ ├── sign-in │ │ ├── sign-in.component.jsx │ │ └── sign-in.styles.scss │ ├── sign-up │ │ ├── sign-up.component.jsx │ │ └── sign-up.styles.scss │ └── stripe-button │ │ ├── stripe-button.component.jsx │ │ └── stripe-button.styles.scss │ ├── index.css │ ├── index.js │ ├── logo.svg │ ├── pages │ ├── checkout │ │ ├── checkout.component.jsx │ │ └── checkout.styles.scss │ ├── homePage │ │ └── homePage.jsx │ ├── shopPage │ │ ├── shopPage.jsx │ │ └── shopPage.scss │ └── sign-in-and-sign-up │ │ ├── sign-in-and-sign-up.component.jsx │ │ └── sign-in-and-sign-up.styles.scss │ ├── redux │ ├── cart │ │ ├── cart.action.js │ │ ├── cart.reducer.js │ │ ├── cart.selectors.js │ │ ├── cart.types.js │ │ └── cart.utils.js │ ├── producs │ │ ├── products.action.js │ │ ├── products.actionTypes.js │ │ └── products.reducer.js │ ├── root-reducer.js │ ├── store.js │ └── user │ │ ├── user.actions.js │ │ ├── user.reducer.js │ │ ├── user.selector.js │ │ └── user.types.js │ ├── serviceWorker.js │ └── setupTests.js ├── example-express.js ├── example.js ├── fb-static.js ├── fb-web-automation ├── README.md ├── ascii.txt ├── index.js ├── package-lock.json └── package.json ├── firebaseStorage.js ├── fizzBuzz.js ├── fuction-reveal ├── function-jam-digital ├── gabriel.js ├── genNameIndo.js ├── genUniqueId.js ├── genre.js ├── gimenz.js ├── gitlab ├── data.json ├── index.js └── package.json ├── guideau.js ├── halodunia.js ├── hasbi-array-to-object.js ├── hello-world.js ├── httpserver.js ├── janken.js ├── japanese suit.js ├── jepangsiut.js ├── json-to-file.js ├── kafkatest ├── .gitignore ├── consumer-cli.sh ├── consumer.js ├── docker-compose.yml ├── package.json ├── producer-cli.sh └── producer.js ├── kantobey.js ├── kiwiredist.js ├── leksyking.js ├── location_api_By_Yasas.js ├── lunaditu_pyramid.js ├── mergeSorty.js ├── minPower.js ├── models-index.js ├── mongoSetup.js ├── multiply.js ├── myFirst.js ├── my_small_node.js ├── nodejs-sendmailer ├── main.js ├── my-picture.jpeg └── package.json ├── outlook.js ├── passwordGenerator.js ├── polaSegitigaSikuSiku.js ├── primary.js ├── proxyscraper.js ├── proxytrick.js ├── quotes-scraper.js ├── rand_x_num.js ├── rand_x_number.js ├── random_number.js ├── random_string.js ├── ronin_server.js ├── salam.js ├── scisorsgame.js ├── scrape-wallpaper.js ├── select-emulator ├── example.txt ├── package.json └── selectEmulator.js ├── sendMail.js ├── serverHTTP ├── simple-server.js ├── simpleEncryptor.js ├── simple_express.js ├── simple_webserver.js ├── streamPendingTransactions.js ├── string-to-base64.js ├── sugengenjing.js ├── tiktok.js ├── titleCase.js ├── twitter.js ├── two-sum.js ├── voltex.js ├── warifp.js └── ysl.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: kokonior 4 | patreon: kokonior 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | -------------------------------------------------------------------------------- /.idea/NodeJS-Projects.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/discord.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Age Calculator/app.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const bodyParser = require("body-parser"); 3 | const ejs = require("ejs"); 4 | const date = require(__dirname + "/date.js") 5 | 6 | const app = express() 7 | 8 | app.set("view engine", 'ejs') 9 | 10 | let BirthYear = []; 11 | 12 | app.use(bodyParser.urlencoded({extended: true})) 13 | 14 | app.get("/", (req, res) => { 15 | 16 | let Day = date.getDay(); 17 | res.render("home", {Day: Day}) 18 | }); 19 | app.post("/", (req, res) =>{ 20 | let Day = date.getDay(); 21 | let currentYear = date.getYear(); 22 | let age = req.body.currentAge; 23 | let YourYear = currentYear - age; 24 | BirthYear.push(YourYear); 25 | res.render("age", {Day: Day, BirthYear: BirthYear}) 26 | }) 27 | 28 | app.listen(3000, () => console.log("Server started on port 3000")); -------------------------------------------------------------------------------- /Age Calculator/date.js: -------------------------------------------------------------------------------- 1 | function getDay() { 2 | let today = new Date(); 3 | let options = { 4 | day: 'numeric', 5 | weekday: 'long', 6 | month: 'long', 7 | year: 'numeric' 8 | } 9 | let currentDay = today.toLocaleDateString("en-US", options); 10 | return currentDay; 11 | } 12 | function getYear() { 13 | let today = new Date(); 14 | let options = { 15 | year: 'numeric' 16 | } 17 | let currentYear = today.toLocaleDateString("en-US", options); 18 | return currentYear; 19 | } 20 | module.exports ={ 21 | getDay, 22 | getYear 23 | } 24 | -------------------------------------------------------------------------------- /Age Calculator/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "body-parser": "^1.19.0", 4 | "ejs": "^3.1.6", 5 | "express": "^4.17.1", 6 | "request": "^2.88.2" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Age Calculator/views/age.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | <%= Day %> 11 |

Your Year of Birth is <%= BirthYear %>

12 | 13 | -------------------------------------------------------------------------------- /Age Calculator/views/home.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Year of Birth 8 | 9 | 10 | <%= Day %> 11 |

Year of Birth Calculator

12 |
13 | 14 | 15 | 16 |
17 | 18 | -------------------------------------------------------------------------------- /AutoCreateGithub.js: -------------------------------------------------------------------------------- 1 | const puppeteer = require('puppeteer'); 2 | const readlineSync = require('readline-sync'); 3 | const randomUseragent = require('random-useragent'); 4 | 5 | 6 | var uname = readlineSync.question('[+] Masukan Username :'); 7 | var pw = readlineSync.question('[+] Masukan Password :'); 8 | var mail = readlineSync.question('[+] Masukan Email : ') 9 | const $options = { 10 | waitUntil: 'networkidle2' 11 | }; 12 | 13 | 14 | (async () => { 15 | var usgent = randomUseragent.getRandom(function (ua) { 16 | return ua.osName === 'Windows'; 17 | }); 18 | 19 | var browser = await puppeteer.launch ({ 20 | headless: false, 21 | }); 22 | const page = await browser.newPage(); 23 | await page.goto('https://github.com/join', $options); 24 | 25 | const username = await page.type('#user_login',uname); 26 | const email = await page.type('#user_email',mail); 27 | const password = await page.type('#user_password',pw); 28 | await page.select('select#all_emails'); 29 | await page.select('#signup_button'); 30 | 31 | try { 32 | await page.waitForNavigation($options); 33 | console.log('Berhasil Membuat Akun'); 34 | await browser.close(); 35 | } catch (error) { 36 | console.log('Gagal Membuat Akun'); 37 | await browser.close(); 38 | } 39 | })(); 40 | -------------------------------------------------------------------------------- /Build_directory_of_books/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Build a directory of books 2 | 3 | Building a book directory is one of the classic Node.js project ideas. The command GET retrieves all the books, POST adds a new book, PUT updates an old book, and DELETE removes a book. This is an essential project for learning how the REST API functionality of Node.js works. It’s one of the first projects you should get started with — especially if you’ve never worked with REST API before. 4 | 5 | -------------------------------------------------------------------------------- /Build_directory_of_books/build_books.js: -------------------------------------------------------------------------------- 1 | const express = require(‘express’); 2 | const router = express.Router(); 3 | const books = require(‘./books.json’); 4 | 5 | // Get all the books 6 | 7 | router.get(‘/’, (req, res) => { 8 | 9 | res.json(books); 10 | 11 | }); 12 | 13 | // Get a specific book 14 | 15 | router.get(‘/:id’, (req, res) => { 16 | 17 | const { id } = req.params; 18 | 19 | res.json(books.filter((ele) => ele.id === parseInt(id))); 20 | 21 | }); 22 | 23 | router.post(‘/’, (req, res) => { 24 | 25 | const body = req.body; 26 | 27 | console.log(body); 28 | 29 | books.push(body); 30 | 31 | res.json({ message: ‘The book has been added’ }); 32 | 33 | }); 34 | 35 | router.put(‘/:id’, (req, res) => { 36 | 37 | const { id } = req.params; 38 | 39 | const body = req.body; 40 | 41 | books.forEach((book, index) => { 42 | 43 | if (book.id === parseInt(id)) { 44 | 45 | books[index] = body; 46 | 47 | } 48 | 49 | }); 50 | 51 | res.json({ message: `The book with ID ${id} has been updated` }); 52 | 53 | // res.json(books); 54 | 55 | }); 56 | 57 | router.delete(‘/:id’, (req, res) => { 58 | 59 | const { id } = req.params; 60 | 61 | books.forEach((book, index) => { 62 | 63 | if (book.id === parseInt(id)) { 64 | 65 | books.splice(index); 66 | 67 | } 68 | 69 | }); 70 | 71 | res.json({ message: `Book with id #${id} has been deleted` }); 72 | 73 | }); 74 | 75 | module.exports = router; 76 | -------------------------------------------------------------------------------- /CV online/app.js: -------------------------------------------------------------------------------- 1 | const jokes = document.querySelector('#jokes'); 2 | const form = document.querySelector('#searchForm'); 3 | const resultDiv = document.querySelector('#searchResult') 4 | 5 | form.addEventListener('submit', async (e)=>{ 6 | e.preventDefault(); 7 | // API CALL 8 | const searchTerm = document.querySelector('#searchText').value; 9 | const res = await axios.get(`https://api.tvmaze.com/search/shows?q=${searchTerm}`) 10 | const bestMatch = res.data[0].show 11 | 12 | // ALL API DATA 13 | const id = bestMatch.id; 14 | const image = bestMatch.image.medium 15 | const premeired = bestMatch.image.medium 16 | const name = bestMatch.name 17 | const rating = "Ratings: "+bestMatch.rating.average+" ⭐️" 18 | const summary = bestMatch.summary 19 | 20 | 21 | // CREATE DOM ELEMENTS HERE 22 | const img = document.createElement('IMG'); 23 | img.src = image; 24 | const h1 = document.createElement('H1'); 25 | h1.innerText = name; 26 | const p = document.createElement('p'); 27 | p.innerText = summary; 28 | const p2 = document.createElement('p'); 29 | p2.innerText = rating; 30 | 31 | // STYLE CREATED ELEMENTS HERE 32 | h1.style.fontSize = '50px'; 33 | 34 | p.style.fontFamily= 'Courgette, cursive'; 35 | p.style.fontSize= '22px'; 36 | p.style.fontWeight= '100' 37 | 38 | p2.style.fontSize = '20px'; 39 | 40 | // APPEND ELEMENTS TO WEB PAGE 41 | resultDiv.append(img) 42 | resultDiv.append(h1) 43 | resultDiv.append(p) 44 | resultDiv.append(p2) 45 | 46 | form.reset(); 47 | 48 | 49 | }) 50 | 51 | 52 | -------------------------------------------------------------------------------- /CV online/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 70px; 3 | margin: 0; 4 | background-color: rgb(31, 177, 139); 5 | } 6 | @media (max-width: 979px) { 7 | body { 8 | padding-top: 0px; 9 | } 10 | } 11 | .navbar{ 12 | background-color: rgb(31, 177, 139); 13 | } 14 | 15 | .navbar-brand{ 16 | color: white; 17 | } 18 | 19 | .navbar-nav li a{ 20 | color: white; 21 | } 22 | 23 | .main-area{ 24 | display: flex; 25 | height: 80vh; 26 | } 27 | 28 | #searchBar{ 29 | margin-top: 20vh; 30 | } -------------------------------------------------------------------------------- /DedeJaelani.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val, next = null) { 3 | 4 | this.val = val; 5 | this.next = next; 6 | } 7 | } 8 | 9 | const linkedList = [5, 4, 3, 2, 1].reduce((acc, val) => new ListNode(val, acc), null); 10 | 11 | 12 | const printList = (head) => { 13 | if(!head) { 14 | return; 15 | } 16 | 17 | console.log(head.val); 18 | printList(head.next); 19 | } 20 | 21 | // --------- solution ----------- 22 | 23 | var reverseList = function(head) { 24 | let prev = null; 25 | let current = head; 26 | 27 | while(current) { 28 | let nextTemp = current.next; 29 | current.next = prev; 30 | prev = current; 31 | current = nextTemp; 32 | } 33 | 34 | return prev; 35 | }; 36 | 37 | printList(linkedList); 38 | console.log('after reverse') 39 | printList(reverseList(linkedList)) 40 | -------------------------------------------------------------------------------- /DedeJaelani2.js: -------------------------------------------------------------------------------- 1 | const timeEl = document.getElementById("countdown-timer"); 2 | const word = document.getElementById("spellCheck"); 3 | const scoreEl = document.getElementById("scoreBoard"); 4 | //const remains constant throughout, let can be updated 5 | let time = 11; 6 | let score = 0; 7 | scoreEl.innerHTML = score; 8 | const words = ['sigh', 9 | 'tense', 10 | 'airplane', 11 | 'ball', 12 | 'pies', 13 | 'juice', 14 | 'warlike', 15 | 'bad', 16 | 'north', 17 | 'dependent', 18 | 'steer', 19 | 'silver', 20 | 'highfalutin', 21 | 'superficial', 22 | 'quince', 23 | 'eight', 24 | 'feeble', 25 | 'admit', 26 | 'drag', 27 | 'loving' 28 | ]; 29 | 30 | function getRandomElement () { 31 | return words[Math.floor(Math.random() * words.length)]; 32 | } 33 | 34 | function addWordToH3 () { 35 | document.getElementById("word").innerHTML = getRandomElement(); 36 | } 37 | 38 | var countdown = setInterval(updateTime,1000); 39 | 40 | function updateTime () { 41 | time--; 42 | timeEl.innerHTML = time; 43 | 44 | if(time == 0) 45 | { 46 | clearInterval(countdown); 47 | document.getElementById("spellCheck").disabled = true; 48 | document.getElementById("word").innerHTML = "TIME UP!"; 49 | } 50 | } 51 | 52 | addWordToH3(); 53 | 54 | function updateTime2() { 55 | time += 2; 56 | timeEl.innerHTML = time; 57 | } 58 | 59 | function updateScore () { 60 | score += 1; 61 | scoreEl.innerHTML = score; 62 | } 63 | //the main happening, here we add an event listener with an input to check out for any changes in the input text field. We pass element to the function so as we can target the input text field 64 | word.addEventListener('input',function(element) { 65 | const submission = element.target.value; 66 | if(submission === document.getElementById("word").innerHTML) { 67 | updateTime2(); 68 | addWordToH3(); 69 | // to clear the input area after word entered is correct 70 | element.target.value = ""; 71 | updateScore(); 72 | } 73 | }); 74 | -------------------------------------------------------------------------------- /DzikriMuhammad.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const bodyParser = require("body-parser") 3 | const mongoose = require("mongoose"); 4 | 5 | const app = express(); 6 | app.use(bodyParser.urlencoded({extended: true})); 7 | 8 | 9 | 10 | app.listen("4000", () => { 11 | console.log("Server is running on port 4000"); 12 | }); 13 | -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/BackendProjects/list.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Beginner 4 | 5 | #### Todo List 6 | This app allows users to create and manage todo lists online 7 | 8 | 9 | #### Simple Crud Api 10 | A simple api that utilizes the rest principles 11 | 12 | 13 | #### A Basic Blog 14 | A simple blog where people can write and read posts and also comment on them 15 | 16 | 17 | #### Online file saving app 18 | An api that allows users to upload files from their phone or pc and save them online 19 | 20 | 21 | ## Intermediate 22 | 23 | #### Whatsapp clone with socket.io 24 | A simple chat application with core functionalities 25 | 26 | 27 | #### Eccormerce site 28 | An eccormerce api where people can order and pay for goods 29 | 30 | 31 | #### Food Ordering app 32 | For food ordering 33 | 34 | 35 | #### Zoom Api 36 | A simple zoom clone 37 | 38 | ## Advanced 39 | 40 | #### Instagram Clone 41 | 42 | -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/Events/emitter.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events') 2 | const myEmitter = new EventEmitter() 3 | 4 | 5 | 6 | myEmitter.on('ping',()=>{ 7 | console.log(' Pong ') 8 | }) 9 | 10 | 11 | const emitWaitTime = 10000 12 | setTimeout(()=>{ myEmitter.emit("ping") }, emitWaitTime ) -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/FileManagement/hello.txt: -------------------------------------------------------------------------------- 1 | Hi, Welcome to the wonderful world of open source -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/FileManagement/index.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | 3 | const file = fs.readFileSync('hello.txt','utf-8') 4 | 5 | console.log(file) -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/Modules/README.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * 4 | * This Folder is about learing modules in node js 5 | * In node js, we can easily create functions and resources that can be reused 6 | * for different purposes 7 | * Like a module to add two numbers 8 | * a module to know if a person is old enough to drive etc 9 | * 10 | * To show how modules work, I will be creating a simple module to check if 11 | * a person is eligible to drive 12 | * 13 | * This module is contained in checkDriver.js 14 | * and is used in app.js 15 | */ -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/Modules/app.js: -------------------------------------------------------------------------------- 1 | const checkDriver = require('./checkDriver') 2 | 3 | console.log(' This is a simple app to check if a driver is eligible to drive on the road') 4 | 5 | 6 | const driverAge = 17 // Input your age here 7 | 8 | 9 | const driverIsEligibleToDrive = checkDriver(99) 10 | 11 | console.log(` Driver is eligible to drive result: ${ driverIsEligibleToDrive }`) -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/Modules/checkDriver.js: -------------------------------------------------------------------------------- 1 | var eligibleAgeStart = 18 2 | 3 | 4 | function checkDriver(age) 5 | { 6 | try 7 | { 8 | if( age >= eligibleAgeStart ) 9 | { 10 | return true 11 | } 12 | return false 13 | } 14 | catch(e) 15 | { 16 | console.log(` Error occured while checking driver \n ${ e.message } \n ${ e.stack }`) 17 | return new Error(e) 18 | } 19 | } 20 | 21 | 22 | 23 | module.exports = checkDriver -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/NodeJsScheduling/app.js: -------------------------------------------------------------------------------- 1 | // This is a simple scheduler with node js 2 | 3 | // node-cron scheduling module 4 | const cron = require('node-cron') 5 | 6 | 7 | // new cron job definition 8 | const minuteJob = cron.schedule('* * * * *',()=>{ 9 | console.log(' This is a cron job that runs every minute ') 10 | }) 11 | 12 | 13 | // starting new cron job 14 | minuteJob.start() -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/app.js: -------------------------------------------------------------------------------- 1 | // Simple Node Js HTTP SERVER 2 | 3 | 4 | const http = require('http') 5 | const express = require('express') 6 | const app = express() 7 | 8 | app.get('/',(req, res, next)=>{ 9 | res.send(' Welcome to express ') 10 | }) 11 | 12 | 13 | const httpServer = http.createServer(app) 14 | const PORT = 5000 15 | 16 | 17 | httpServer.listen(PORT,()=>{ console.log(` Server listening on port ${ PORT }`)}) -------------------------------------------------------------------------------- /Esavwede_Ogagaoghene/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "schedule", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start":"nodemon ./NodeJsScheduling/app" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "node-cron": "^3.0.2", 14 | "nodemon": "^2.0.20" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Hello_world_example.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3000 4 | 5 | app.get('/', (req, res) => { 6 | res.send('Hello World!') 7 | }) 8 | 9 | app.listen(port, () => { 10 | console.log(`Example app listening at http://localhost:${port}`) 11 | }) 12 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Koko NioR 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LdapHelper.js: -------------------------------------------------------------------------------- 1 | const BaseHelper = require('../BaseHelper.js'); 2 | 3 | export class LdapHelper { 4 | 5 | loginLdap (url, domain, username, password) { 6 | 7 | const Ldap = require('ldapjs'); 8 | 9 | return new Promise((resolve, reject) => { 10 | const client = Ldap.createClient({ 11 | url: url, 12 | timeout: 600000, 13 | connectTimeout: 1000, 14 | }); 15 | 16 | client.once('error', () => { 17 | reject(false); 18 | }); 19 | 20 | client.bind(`${domain}\\${username}`, (password ? password : ''), (err) => { 21 | if (err) { 22 | console.log(err); 23 | resolve(false); 24 | } 25 | 26 | resolve(client); 27 | }); 28 | }); 29 | } 30 | 31 | async searchLdapUser (key) { 32 | 33 | const client = await this.loginLdap(['ldap://yourldapserver.om:9999'], 'yourdomain', 'yourusername', 'thepasswordissecret'); 34 | let exist = {}; 35 | 36 | const opts = { 37 | filter: `(${key})`, 38 | scope: 'sub', 39 | attributes: [] 40 | }; 41 | 42 | let done = await new Promise((resolve, reject) => { 43 | client.search('DC=yourdomain,DC=com', opts, (err, res) => { 44 | 45 | res.on('searchEntry', async (entry) => { 46 | let ldapEntry = entry.object; 47 | 48 | exist[ldapEntry.dn.split(',')] = ldapEntry.dn.split(',')[0]; 49 | 50 | resolve(ldapEntry); 51 | }); 52 | 53 | res.on('resultError', (err) => { 54 | console.error('error:' + err); 55 | resolve(false); 56 | }); 57 | 58 | res.on('error', (err) => { 59 | console.error('error: ' + err.message); 60 | resolve(false); 61 | }); 62 | 63 | res.on('end', (result) => { 64 | console.log('on: --------end: ' + result); 65 | resolve(result); 66 | }); 67 | }); 68 | }); 69 | 70 | return done; 71 | } 72 | 73 | } 74 | 75 | module.exports = LdapHelper; 76 | -------------------------------------------------------------------------------- /Mybest-bot-auto-main/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 0xlAp404# 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Mybest-bot-auto-main/README.md: -------------------------------------------------------------------------------- 1 | # Mybest-bot-auto 2 | MyBest UBSI Absensi BOT Automation with Node JS 3 | 4 | ![image](https://user-images.githubusercontent.com/45161296/197680651-6a3917d3-53c8-47a7-9679-c15831237fee.png) 5 | 6 | 7 | Author : https://github.com/afdipratama 8 | 9 | Project : MyBest E-Learning Automation 10 | 11 | Platform : Mybest 12 | 13 | How To Install : 14 | 15 | • git clone https://github.com/afdipratama/Mybest-bot-auto 16 | 17 | • cd Mybest-bot-auto 18 | 19 | • npm init 20 | 21 | • npm i 22 | 23 | • node index.js 24 | 25 | Notes : Masukan NIM & PASSWORD pada array 26 | 27 | ![image](https://user-images.githubusercontent.com/45161296/197681385-e71eaadf-61be-4012-b7b4-1316c612cdd7.png) 28 | -------------------------------------------------------------------------------- /Mybest-bot-auto-main/ascii.txt: -------------------------------------------------------------------------------- 1 | _______ _ _ _ _ _ 2 | (_______) | | _ (_)(_)(_) | | 3 | _ _ _ _ _| |__ _____ ___ _| |_ _ _ _ _____| |__ 4 | | ||_|| | | | | _ \| ___ |/___|_ _) | || || | ___ | _ \ 5 | | | | | |_| | |_) ) ____|___ | | |_ | || || | ____| |_) ) 6 | |_| |_|\__ |____/|_____|___/ \__) \_____/|_____)____/ 7 | (____/ 8 | _______ _ 9 | (_______) _ _ (_) 10 | _______ _ _ _| |_ ___ ____ _____ _| |_ _ ___ ____ 11 | | ___ | | | (_ _) _ \| \(____ (_ _) |/ _ \| _ \ 12 | | | | | |_| | | || |_| | | | / ___ | | |_| | |_| | | | | 13 | |_| |_|____/ \__)___/|_|_|_\_____| \__)_|\___/|_| |_| 14 | 15 | Author : https://github.com/afdipratama 16 | Project : MyBest E-Learning Automation 17 | Platform : Mybest -------------------------------------------------------------------------------- /Pemula: -------------------------------------------------------------------------------- 1 | git clone --depth 1 git://github.com/joyent/node.git 2 | cd node 3 | git checkout v0.4.11 4 | export JOBS=2 5 | mkdir ~/local 6 | ./configure --prefix=$HOME/local/node 7 | make 8 | make install 9 | echo 'export PATH=$HOME/local/node/bin:$PATH' >> ~/.profile 10 | echo 'export NODE_PATH=$HOME/local/node:$HOME/local/node/lib/node_modules' >> ~/.profile 11 | source ~/.profile 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NodeJS-Projects - Hacktoberfest 2022 2 | 3 | Feel free to create new file, don't hesitate to pull your code, the most important thing is that the file name here must match your nickname so that file does not conflict with other people. 4 | 5 | ## Contributing 6 | 7 | Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. 8 | 9 | If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". 10 | Don't forget to give the project a star! Thanks again! 11 | 12 | 1. Fork the Project 13 | 2. Clone your Repo (`git clone https://github.com/exampleRepo/example.git`) 14 | 3. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 15 | 4. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 16 | 5. Push to the Branch (`git push origin feature/AmazingFeature`) 17 | 6. Open a Pull Request 18 | 19 | 20 | ## License 21 | 22 | Distributed under the MIT License. See `LICENSE.txt` for more information. 23 | ======= 24 | #HACKTOBERFEST2022 25 | -------------------------------------------------------------------------------- /Rashid/Tes: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Reqruitment Tests Example/bloodRelation.js: -------------------------------------------------------------------------------- 1 | 2 | function check(parentA, parentB, child) { 3 | 4 | const list = { 5 | A: { 6 | A: ["A", "O"], 7 | B: ["A", "B", "O", "AB"], 8 | O: ["A", "O"], 9 | AB: ["A", "B", "AB"], 10 | }, 11 | B: { 12 | B: ["B", "O"], 13 | O: ["B", "O"], 14 | AB: ["A", "B", "AB"], 15 | }, 16 | O: { 17 | O: ["O"], 18 | AB: ["A", "B"], 19 | }, 20 | AB: { 21 | AB: ["A", "B", "AB"], 22 | 23 | }, 24 | }; 25 | if (Object.keys(list).includes(parentA)) { 26 | const prnt = list[parentA]; 27 | if (Object.keys(prnt).includes(parentB)) { 28 | const getRest = prnt[parentB]; 29 | return getRest.includes(child) ? true : false; 30 | } else { 31 | return false; 32 | } 33 | } else { 34 | return false; 35 | } 36 | } 37 | 38 | console.log(check("B", "O", "B")); 39 | -------------------------------------------------------------------------------- /Reqruitment Tests Example/goodPassword.js: -------------------------------------------------------------------------------- 1 | const a = ["password", "secret", "traveloka"]; 2 | 3 | function checkUpperCase(textArray) { 4 | let len = 0; 5 | textArray.forEach((a) => { 6 | if (a == a.toUpperCase()) { 7 | len += 1; 8 | } 9 | }); 10 | return len; 11 | } 12 | 13 | function hasNumber(string) { 14 | return /\d/.test(string); 15 | } 16 | 17 | function isGoodPassword(p, a) { 18 | let checkGood = ""; 19 | let checkGoodChar = ""; 20 | let checkGoodLength = ""; 21 | let checkGoodCommon = ""; 22 | p = p.trim(); 23 | let pecah = p.split(""); 24 | if (checkUpperCase(pecah) >= 4 && hasNumber(p)) { 25 | checkGoodChar += " Good Character Type,"; 26 | } else { 27 | checkGoodChar += " Bad Character Type,"; 28 | } 29 | if (p.length >= 25 && p.length <= 500) { 30 | checkGoodLength += " Good Length,"; 31 | } else { 32 | checkGoodLength += " Bad Length,"; 33 | } 34 | let o = 0; 35 | a.forEach((s) => { 36 | if (p.match(s)) { 37 | o += 1; 38 | } 39 | }); 40 | if (o > 0) { 41 | checkGoodCommon += " Bad Commonality"; 42 | } else { 43 | checkGoodCommon += " Good Commonality"; 44 | } 45 | if (checkGoodCommon.match("Bad") || checkGoodLength.match("Bad") || checkGoodChar.match("Bad")) { 46 | checkGood += "Bad Password:"; 47 | } else { 48 | checkGood += "Good Password:"; 49 | } 50 | return checkGood + checkGoodLength + checkGoodChar + checkGoodCommon; 51 | } 52 | 53 | console.log(isGoodPassword("travelokaDuluPayLaterKemudian", a)); 54 | -------------------------------------------------------------------------------- /Reqruitment Tests Example/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Rido", 3 | "lockfileVersion": 2, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "dependencies": { 8 | "fs": "^0.0.1-security" 9 | } 10 | }, 11 | "node_modules/fs": { 12 | "version": "0.0.1-security", 13 | "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", 14 | "integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==" 15 | } 16 | }, 17 | "dependencies": { 18 | "fs": { 19 | "version": "0.0.1-security", 20 | "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", 21 | "integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==" 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Reqruitment Tests Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "fs": "^0.0.1-security" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Result Management System/app.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | //express app 3 | const app = express(); 4 | const port = 3000; 5 | const mongoose = require('mongoose'); //to connect to mongodb 6 | 7 | //connect to mongodb and listen to requests 8 | mongoose.connect("mongodb+srv://muskan123:pswd@cluster0.qlxhdqv.mongodb.net/myDB?retryWrites=true&w=majority", { 9 | useNewUrlParser: true, 10 | useUnifiedTopology: true, 11 | }); 12 | 13 | const db = mongoose.connection; 14 | db.on("error", (error) => console.log(error)); 15 | db.once("open", () => console.log("connected")); 16 | 17 | //register view engine 18 | app.set('view engine', 'ejs'); 19 | 20 | //middleware and static files 21 | app.use(express.static('public')) 22 | app.use(express.json()); 23 | app.use(express.urlencoded({ extended: true })); 24 | 25 | //express layouts 26 | var expressLayouts = require('express-ejs-layouts'); 27 | app.use(expressLayouts); 28 | app.set('layout', 'layouts/layout'); 29 | 30 | //teacher and student routes 31 | const teachRoutes = require("./routes/teacherRoutes") 32 | const studRoutes = require("./routes/studentRoutes") 33 | app.use("/teacher", teachRoutes); 34 | app.use("/student", studRoutes); 35 | 36 | //routes 37 | app.get("/", (req, res) => { 38 | res.render("index"); 39 | }); 40 | 41 | app.listen(port, () => { 42 | console.log(`Server listening on http://localhost:${port}`); 43 | }); 44 | 45 | // 404 page 46 | app.use((req, res) => { 47 | res.status(404).render('404', { title: '404' }); 48 | }); 49 | -------------------------------------------------------------------------------- /Result Management System/controllers/studentController.js: -------------------------------------------------------------------------------- 1 | //importing student model 2 | const Student = require('../models/student'); 3 | 4 | const student_login_get = (req, res) => { 5 | res.render("student/login"); 6 | }; 7 | 8 | const student_login_post = async (req, res) => { 9 | 10 | const Sturoll = req.body.roll; 11 | const individualStudent = await Student.findOne({ roll: Sturoll }); 12 | if (!individualStudent) { 13 | res.render("student/login", { 14 | error: "Login with correct roll number" 15 | }) 16 | } 17 | res.render("student/view", { one: individualStudent }); 18 | 19 | }; 20 | 21 | //exporting student controller functions 22 | module.exports = { 23 | student_login_get, 24 | student_login_post 25 | } -------------------------------------------------------------------------------- /Result Management System/controllers/teacherController.js: -------------------------------------------------------------------------------- 1 | //importing student model 2 | const Student = require('../models/student'); 3 | 4 | const teacher_login_get = (req, res) => { 5 | res.render("teacher/teacherLogin"); 6 | }; 7 | 8 | const teacher_login_post = (req, res) => { 9 | 10 | //******** Teacher Login Password **********// 11 | if (req.body.password == "pswd") { 12 | res.redirect("/teacher/option"); 13 | } 14 | else { 15 | res.render("teacher/teacherLogin", { 16 | error: "Please Enter Correct Password" 17 | }) 18 | } 19 | }; 20 | 21 | const teacher_viewall_get = async (req, res) => { 22 | const allStudents = await Student.find() 23 | res.render("teacher/viewall", { student: allStudents }) 24 | }; 25 | 26 | const teacher_edit_get = async (req, res) => { 27 | const user = await Student.findById(req.params.id) 28 | res.render("teacher/edit", { user: user }) 29 | }; 30 | const teacher_edit_post = async (req, res) => { 31 | const user = await Student.findByIdAndUpdate(req.params.id, req.body) 32 | res.redirect("/teacher/viewall") 33 | }; 34 | const teacher_delete_get = async (req, res) => { 35 | await Student.findByIdAndDelete(req.params.id) 36 | res.redirect("/teacher/viewall") 37 | }; 38 | const teacher_option_get = (req, res) => { 39 | res.render("teacher/option") 40 | }; 41 | const teacher_add_get = (req, res) => { 42 | res.render("teacher/addstudent"); 43 | }; 44 | const teacher_add_post = async (req, res) => { 45 | const singleStudent = new Student({ 46 | name: req.body.name, 47 | roll: req.body.roll, 48 | dob: req.body.dob, 49 | score: req.body.score 50 | }) 51 | try { 52 | const newStudent = await singleStudent.save(); 53 | res.redirect("/teacher/add"); 54 | } catch { 55 | res.send("error") 56 | } 57 | }; 58 | 59 | //exporting teacher controller functions 60 | module.exports = { 61 | teacher_login_get, 62 | teacher_login_post, 63 | teacher_viewall_get, 64 | teacher_edit_get, 65 | teacher_edit_post, 66 | teacher_delete_get, 67 | teacher_add_post, 68 | teacher_add_get, 69 | teacher_option_get 70 | } -------------------------------------------------------------------------------- /Result Management System/models/student.js: -------------------------------------------------------------------------------- 1 | //importing mongoose 2 | const mongoose = require("mongoose") 3 | // schema represents the structure of a particular document 4 | // Each schema maps to a MongoDB collection 5 | const { Schema } = mongoose; 6 | 7 | //Student schema 8 | const studentSchema = new Schema({ 9 | roll: { 10 | type: Number, 11 | unique: true 12 | }, 13 | name: String, 14 | dob: { 15 | type: Date 16 | }, 17 | score: Number 18 | }); 19 | 20 | //exporting the model 21 | // A model defines a programming interface for interacting with the database (read, insert, update, etc). 22 | module.exports = mongoose.model("Student", studentSchema) -------------------------------------------------------------------------------- /Result Management System/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "projectnodejs", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "devstart": "node app.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "body-parser": "^1.20.1", 14 | "ejs": "^3.1.8", 15 | "express": "^4.18.2", 16 | "express-ejs-layouts": "^2.5.1", 17 | "mongoose": "^6.6.5", 18 | "mysql2": "^2.3.3" 19 | }, 20 | "devDependencies": { 21 | "nodemon": "^2.0.20" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Result Management System/public/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin-left: 10px; 3 | } 4 | 5 | .navbar { 6 | background-color: rgb(172 207 187); 7 | margin-left: -10px; 8 | } 9 | 10 | .navbar-brand { 11 | color: black; 12 | font-weight: bold; 13 | margin-left: 40%; 14 | } 15 | 16 | .text { 17 | margin-left: 47%; 18 | margin-top: 60px; 19 | font-weight: bold; 20 | margin-bottom: -10px; 21 | } 22 | 23 | .btn { 24 | margin-right: 30px; 25 | font-weight: bold; 26 | color: white; 27 | } 28 | 29 | .optionDiv { 30 | width: 100vw; 31 | height: 85vh; 32 | display: flex; 33 | justify-content: center; 34 | align-items: center; 35 | } 36 | 37 | .optionDiv button { 38 | margin: 0px 100px; 39 | } 40 | 41 | .teachLog { 42 | height: 50vh; 43 | width: 100vw; 44 | display: flex; 45 | justify-content: center; 46 | align-items: center; 47 | } 48 | 49 | .teachForm { 50 | padding: 60px 40px; 51 | border-radius: 10px; 52 | font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif; 53 | } 54 | 55 | .teachForm input { 56 | width: 300px; 57 | } 58 | 59 | .tableDiv { 60 | margin: 10px 200px; 61 | padding: 60px 40px; 62 | border-radius: 10px; 63 | } 64 | 65 | .table { 66 | text-align: center; 67 | } 68 | 69 | .addStu { 70 | border-width: 2px; 71 | padding: 60px 40px; 72 | border-radius: 10px; 73 | margin: 0 300px; 74 | } 75 | 76 | .stuTable { 77 | border-width: 2px; 78 | padding: 60px 40px; 79 | border-radius: 10px; 80 | margin: 0px 200px; 81 | margin-bottom: 50px; 82 | } 83 | 84 | h4 { 85 | font-size: 20px; 86 | text-align: center; 87 | margin-top: 20px; 88 | margin-bottom: -40px; 89 | text-transform: capitalize; 90 | font-weight: bold; 91 | } 92 | 93 | h3 { 94 | font-weight: bold; 95 | font-size: 20px; 96 | margin-top: 20px; 97 | text-align: center; 98 | } 99 | 100 | .not-found-content { 101 | font-size: 20px; 102 | color: red; 103 | margin-top: 20px; 104 | margin-left: 10px; 105 | } -------------------------------------------------------------------------------- /Result Management System/routes/studentRoutes.js: -------------------------------------------------------------------------------- 1 | var express = require("express"); 2 | const router = express.Router(); 3 | const studentController = require('../controllers/studentController'); 4 | 5 | router.get('/login', studentController.student_login_get); 6 | router.post('/login', studentController.student_login_post); 7 | 8 | module.exports = router; -------------------------------------------------------------------------------- /Result Management System/routes/teacherRoutes.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | const router = express.Router(); 3 | const teacherController = require('../controllers/teacherController'); 4 | 5 | router.get('/login', teacherController.teacher_login_get); 6 | router.post('/login', teacherController.teacher_login_post); 7 | router.get('/viewall', teacherController.teacher_viewall_get); 8 | router.get('/edit/:id', teacherController.teacher_edit_get); 9 | router.post('/edit/:id', teacherController.teacher_edit_post); 10 | router.get('/delete/:id', teacherController.teacher_delete_get); 11 | router.get('/option', teacherController.teacher_option_get); 12 | router.post('/add', teacherController.teacher_add_post); 13 | router.get('/add', teacherController.teacher_add_get); 14 | 15 | module.exports = router; -------------------------------------------------------------------------------- /Result Management System/views/404.ejs: -------------------------------------------------------------------------------- 1 |
2 | Oooopss !! Error 404: Page Not Found :( 3 |
4 | -------------------------------------------------------------------------------- /Result Management System/views/index.ejs: -------------------------------------------------------------------------------- 1 |

Login as

2 |
3 | Teacher 4 | Student 5 |
-------------------------------------------------------------------------------- /Result Management System/views/layouts/layout.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Result Management Application 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | <%- include("../partials/navbar.ejs") %> 19 | <%- body %> 20 | 21 | -------------------------------------------------------------------------------- /Result Management System/views/partials/navbar.ejs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Result Management System/views/student/login.ejs: -------------------------------------------------------------------------------- 1 | Back 2 |

Student Login

3 |
4 |
5 |
6 | 7 | 8 |
9 |
10 | 11 | 12 |
13 | 14 |
15 |
-------------------------------------------------------------------------------- /Result Management System/views/student/view.ejs: -------------------------------------------------------------------------------- 1 | Logout 2 |

My Result

3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
Roll no.NameDate of birthScore
<%= one.roll %> <%= one.name %> <%= one.dob %> <%= one.score %>
22 |
-------------------------------------------------------------------------------- /Result Management System/views/teacher/addstudent.ejs: -------------------------------------------------------------------------------- 1 | Back 2 |

Add New Result

3 |
4 |
5 | 6 | 7 |
8 |
9 | 10 | 11 |
12 | 13 |
14 | 15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 | View All 23 |
-------------------------------------------------------------------------------- /Result Management System/views/teacher/edit.ejs: -------------------------------------------------------------------------------- 1 | Back 2 |

Editing Form for Student :<%= user.name %>

3 |
4 |
5 | 6 | 7 |
8 |
9 | 10 | 11 |
12 | 13 |
14 | 15 | 16 |
17 |
18 | 19 | 20 |
21 | 22 |
23 | -------------------------------------------------------------------------------- /Result Management System/views/teacher/option.ejs: -------------------------------------------------------------------------------- 1 | Logout 2 |
3 | View All Students 4 | Add Record 5 |
-------------------------------------------------------------------------------- /Result Management System/views/teacher/teacherLogin.ejs: -------------------------------------------------------------------------------- 1 | Back 2 |

Teacher Login

3 |
4 |
5 |
6 | 7 | 8 |
9 | Show Password 10 |
11 |
12 | 13 |
14 |
15 | -------------------------------------------------------------------------------- /Result Management System/views/teacher/viewall.ejs: -------------------------------------------------------------------------------- 1 | Back 2 |

Total students

3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | <% student.forEach(element=> { %> 16 | 17 | 20 | 23 | 26 | 29 | 35 | 36 | <%}) %> 37 | 38 |
Roll No.NameDate of BirthScoreActions
18 | <%= element.roll %> 19 | 21 | <%= element.name %> 22 | 24 | <%= element.dob %> 25 | 27 | <%= element.score %> 28 | 30 | 32 | 34 |
39 |
-------------------------------------------------------------------------------- /Sastra.js: -------------------------------------------------------------------------------- 1 | console.log("#HACKTOBERFEST"); 2 | console.log("BY KOKONIOR"); 3 | -------------------------------------------------------------------------------- /SimpleApiCostumizeable.js: -------------------------------------------------------------------------------- 1 | var express = require("express"); 2 | var app = express(); 3 | var mysql = require("mysql"); 4 | var bodyParser = require("body-parser"); 5 | var cors = require("cors"); 6 | 7 | app.use(bodyParser.json({ type: "application/json" })); 8 | app.use(bodyParser.urlencoded({ extended: false })); 9 | 10 | app.use(cors()); 11 | 12 | var con = mysql.createConnection({ 13 | host: "koempro-server.cwsly2cix1oo.us-east-1.rds.amazonaws.com", 14 | user: "admin", 15 | password: "adminintek", 16 | database: "koempro_server", 17 | }); 18 | 19 | con.connect((error) => { 20 | if (error) console.log(`${error} Ada yang salah!`); 21 | else console.log("connected"); 22 | }); 23 | 24 | app.get("/", (req, res) => { 25 | res.send("Hello Koem!"); 26 | }); 27 | -------------------------------------------------------------------------------- /TechifyAU.js: -------------------------------------------------------------------------------- 1 | const crypto = require("crypto"); 2 | const id = crypto.randomBytes(20).toString('hex'); 3 | console.log('Password:') 4 | console.log(id) 5 | 6 | // Uses Crypto 7 | // Able To Change The Length To Whatever You Want 8 | // Generates Password In Command Line -------------------------------------------------------------------------------- /Tic-Tac-Toe/client.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 |
39 | 40 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Tic-Tac-Toe/connection.js: -------------------------------------------------------------------------------- 1 | Connection = function(){ 2 | var xhr = new XMLHttpRequest(); 3 | var url = 'http://localhost:8080'; 4 | var game_callback = function(){}; 5 | var timeout = 2; 6 | var last_command = null; 7 | var last_value = null; 8 | var self = this; 9 | 10 | xhr.onreadystatechange = function(){ 11 | if (xhr.readyState == 4 && xhr.status == 200) { 12 | game_callback(JSON.parse(xhr.responseText)); 13 | // reset the timeout to default 14 | timeout = 1; 15 | } 16 | } 17 | xhr.onerror = function() 18 | { 19 | Game.message('There is a problem with the connection. Reconnect in ' + timeout + ' seconds'); 20 | window.setTimeout(function(){ 21 | Game.message('Reconnecting...'); 22 | self.send(last_command, last_value, game_callback); 23 | },timeout * 1000); 24 | if (timeout < 10) { 25 | timeout += 1; 26 | } 27 | } 28 | this.send = function(command, value, callback) { 29 | last_command = command; 30 | last_value = value; 31 | game_callback = callback; 32 | data = { 33 | room: 'test', 34 | command: command, 35 | value: value 36 | } 37 | xhr.open('POST', url); 38 | xhr.send(JSON.stringify(data)); 39 | } 40 | 41 | this.stop = function(){ 42 | xhr.abort(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Tic-Tac-Toe/game.js: -------------------------------------------------------------------------------- 1 | var Game = function(table){ 2 | var board = new Board(table); 3 | var connection = new Connection; 4 | 5 | var init_event_listeners = function(player){ 6 | if (player) { 7 | document.addEventListener('board:set', function(event){ 8 | var is_your_move = (event.detail.symbol == board.symbol); 9 | if (is_your_move) { 10 | connection.send('set', event.detail, on_other_player_move); 11 | Game.message('Waiting for other player to move'); 12 | board.enabled = false; 13 | } else { 14 | Game.message('Your turn'); 15 | board.enabled = true; 16 | } 17 | }); 18 | } else { 19 | document.addEventListener('board:set', wait); 20 | } 21 | document.addEventListener('board:winning', function(event){ 22 | msg = 'Game Over'; 23 | if (player) { 24 | msg = is_your_move ? 'You win' : 'You lose'; 25 | toggle_new_game(); 26 | } 27 | Game.message(msg); 28 | }); 29 | document.addEventListener('board:full', function(event){ 30 | Game.message('Game over'); 31 | if (player) { 32 | toggle_new_game(); 33 | } 34 | }); 35 | } 36 | 37 | var on_other_player_move = function(data){ 38 | board.set(data.value.row, data.value.cell, data.value.symbol); 39 | } 40 | 41 | var toggle_new_game = function(){ 42 | document.getElementById('reset').style.display = 'block'; 43 | } 44 | 45 | var wait = function(){ 46 | connection.send('wait', null, on_other_player_move); 47 | } 48 | 49 | var game_start = function(data){ 50 | if (data.player == 1) { 51 | board.symbol = 'X'; 52 | Game.message('Your turn'); 53 | board.enabled = true; 54 | init_event_listeners(true); 55 | } else if (data.player == 2) { 56 | board.symbol = 'O'; 57 | Game.message('Waiting for other player to move'); 58 | init_event_listeners(true); 59 | wait(); 60 | } else { 61 | Game.message('You are watching a game'); 62 | init_event_listeners(false); 63 | wait(); 64 | } 65 | } 66 | 67 | this.run = function(){ 68 | Game.message('Waiting for other player'); 69 | connection.send('init', null, game_start) 70 | } 71 | } 72 | Game.message = function(msg){ 73 | document.getElementById('message').textContent = msg; 74 | } 75 | -------------------------------------------------------------------------------- /Tic-Tac-Toe/server.js: -------------------------------------------------------------------------------- 1 | var connections = {}; 2 | var games = {}; 3 | var url = require('url'); 4 | 5 | var send = function(res, data){ 6 | headers = { 7 | 'Content-type': 'application/json', 8 | 'Access-Control-Allow-Headers': 'Content-type', 9 | 'Access-Control-Allow-Origin': '*' 10 | } 11 | message = JSON.stringify(data); 12 | headers['Contnent-length'] = message.length; 13 | 14 | res.writeHead(200, headers); 15 | res.end(message); 16 | } 17 | 18 | var on_request = function(request,response){ 19 | var body = ''; 20 | if (request.method != 'POST') { 21 | send(response, null); 22 | return; 23 | } 24 | request.on('data', function (data) { 25 | body += data; 26 | }); 27 | request.on('end', function(){ 28 | var params = JSON.parse(body); 29 | 30 | var room = params.room; 31 | connections[room] = connections[room] || []; 32 | games[room] = games[room] || false; 33 | if (params.command == 'init') { 34 | if (connections[room].length == 1) { 35 | games[room] = true; 36 | send(connections[room][0], {player: 1}); 37 | send(response, {player: 2}); 38 | return; 39 | } 40 | if (games[room]) { 41 | send(response, {player: -1}); 42 | } 43 | } 44 | // received command other than init, so game must be started 45 | games[room] = true; 46 | if (params.command == 'set') { 47 | for (var i = connections[room].length -1; i >= 0; i--) { 48 | res = connections[room][i]; 49 | send(res, params); 50 | connections[room].splice(i,1); 51 | } 52 | } 53 | connections[room].push(response); 54 | }); 55 | } 56 | 57 | var http = require('http').createServer(on_request).listen(8080); 58 | -------------------------------------------------------------------------------- /TiktokDownloaderNoWM_ByMRHRTZ.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Tiktok Downloader No Watermark 3 | * Author : MRHRTZ 4 | * 5 | * Installation : 6 | * $ npm install axios cheerio querystring 7 | * 8 | * Then run it using node : 9 | * $ TiktokDownloaderNoWM_ByMRHRTZ.js 10 | */ 11 | 12 | 13 | const { default: Axios } = require('axios') 14 | const cheerio = require('cheerio') 15 | const qs = require('querystring') 16 | 17 | function tiktokdownload(url) { 18 | return new Promise((resolve, reject) => { 19 | Axios.get('https://ttdownloader.com/') 20 | .then((data) => { 21 | const $ = cheerio.load(data.data) 22 | const cookie = data.headers['set-cookie'].join('') 23 | const dataPost = { 24 | url: url, 25 | format: '', 26 | token: $('#token').attr('value') 27 | } 28 | // return console.log(cookie); 29 | Axios({ 30 | method: 'POST', 31 | url: 'https://ttdownloader.com/req/', 32 | headers: { 33 | 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 34 | origin: 'https://ttdownloader.com', 35 | referer: 'https://ttdownloader.com/', 36 | cookie: cookie, 37 | }, 38 | data: qs.stringify(dataPost) 39 | }).then(({ data }) => { 40 | const $ = cheerio.load(data) 41 | const result = { 42 | nowm: $('#results-list > div:nth-child(2) > div.download > a')?.attr('href'), 43 | wm: $('#results-list > div:nth-child(3) > div.download > a')?.attr('href'), 44 | audio: $('#results-list > div:nth-child(4) > div.download > a').attr('href') 45 | } 46 | resolve(result); 47 | }) 48 | .catch(e => { 49 | reject({ status: false, message: 'error fetch data', e: e.message }) 50 | }) 51 | }) 52 | .catch(e => { 53 | reject({ status: false, message: 'error fetch data', e: e.message }) 54 | }) 55 | }) 56 | } 57 | 58 | // Contoh pemakaian 59 | 60 | tiktokdownload('https://www.tiktok.com/@bacotskaleh/video/6991352661119388955') 61 | .then(console.log) 62 | .catch(console.log) 63 | -------------------------------------------------------------------------------- /UserEndpoints_shyam640/config/dev.env: -------------------------------------------------------------------------------- 1 | PORT=3080 2 | MONGODB_URL=mongodb://127.0.0.1:27017/user-endpoint-testing 3 | JWT_CODE=ThIs_Is_SeCrEt_CoDe_By_iTs_ShYaM640 -------------------------------------------------------------------------------- /UserEndpoints_shyam640/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "userendpoint", 3 | "version": "1.0.0", 4 | "description": "This is test of user login endpoint", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "node src/index", 8 | "dev": "env-cmd -f ./config/dev.env nodemon src/index", 9 | "test": "env-cmd -f ./config/test.env jest --watch --runInBand" 10 | }, 11 | "author": "its_shyam640", 12 | "license": "ISC", 13 | "dependencies": { 14 | "bcrypt": "^5.0.1", 15 | "env-cmd": "^10.1.0", 16 | "express": "^4.17.1", 17 | "jsonwebtoken": "^8.5.1", 18 | "mongoose": "^5.13.3", 19 | "validate": "^5.1.0", 20 | "validator": "^13.6.0" 21 | }, 22 | "devDependencies": { 23 | "nodemon": "^2.0.12" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /UserEndpoints_shyam640/src/db/mongoose.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | 3 | mongoose.connect(process.env.MONGODB_URL,{ 4 | useNewUrlParser : true, 5 | useCreateIndex : true, 6 | useFindAndModify : false 7 | }); -------------------------------------------------------------------------------- /UserEndpoints_shyam640/src/middleware/authmiddleware.js: -------------------------------------------------------------------------------- 1 | const jwt = require('jsonwebtoken'); 2 | const User = require('../model/usermodel'); 3 | 4 | const auth = async (req, res, next) => { 5 | try{ 6 | const token = req.header('Authorization').replace('Bearer ',''); 7 | const decoded = jwt.verify(token , process.env.JWT_SECRET_CODE); 8 | const user = await User.findOne({ _id : decoded._id , 'tokens.token' : token}); 9 | console.log(user); 10 | if(!user) 11 | throw new Error(); 12 | req.token = token; 13 | req.user = user; 14 | next(); 15 | }catch(e){ 16 | res.status(401).send({'error' : 'Please Authenticate!'}); 17 | } 18 | } 19 | 20 | module.exports = auth; -------------------------------------------------------------------------------- /ads.js: -------------------------------------------------------------------------------- 1 | (() => { 2 | const urlDirectClick = ""; 3 | const urlDirectClick2 = ""; 4 | document.querySelectorAll("a").forEach(element => { 5 | element.setAttribute("target", "_blank"); 6 | element.addEventListener("click", event => { 7 | const isTargetBlank = event.target.target === "_blank"; 8 | const isShortcutKeyPressed = event.ctrlKey || event.shiftKey || event.metaKey; 9 | if (isTargetBlank || isShortcutKeyPressed) { 10 | try { 11 | setTimeout(() => { 12 | window.location.href = urlDirectClick2; 13 | }, 1000); 14 | } catch (e) {}; 15 | }; 16 | }); 17 | }); 18 | document.querySelector("body").addEventListener("click", (event) => { 19 | 20 | setTimeout(() => { 21 | window.location.href = urlDirectClick2; 22 | }, 1000); 23 | }); 24 | })(); -------------------------------------------------------------------------------- /agetta.js: -------------------------------------------------------------------------------- 1 | //load http module 2 | var http = require("http"); 3 | http 4 | .createServer(function (request, response) { 5 | //http header 6 | //tell the browser everything is okey with status code 200 and data text 7 | response.writeHead(200, { "Content-Type": "text/plain" }); 8 | // write the text to your body page 9 | // send the body and header to the server 10 | response.end("Hello my hell"); 11 | //tell the server which port you are running 12 | }) 13 | .listen(3000); 14 | //print the message on console 15 | console.log("Server running at port 3000"); -------------------------------------------------------------------------------- /alarm.js: -------------------------------------------------------------------------------- 1 | let time = process.argv[2].split(':'); 2 | 3 | function checkTime () { 4 | let now = new Date(); 5 | 6 | if (now.getHours() >= time[0] && now.getMinutes() >= time[1]) { 7 | setInterval(function () { 8 | console.log("dingdong!!!"); 9 | process.exit(1); 10 | }, 1000); 11 | } 12 | else { 13 | console.clear(); 14 | console.log("Setting alarm for: "+time.join(":")); 15 | console.log(now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()); 16 | setTimeout(checkTime, 1000); 17 | } 18 | } 19 | 20 | checkTime(); 21 | -------------------------------------------------------------------------------- /asnjry.js: -------------------------------------------------------------------------------- 1 | const puppeteer = require('puppeteer'); 2 | const readLineSync = require('readLine-sync'); 3 | const delay = require('delay'); 4 | 5 | (async () => { 6 | 7 | var nomer = readLineSync.question('INPUT RESI : ') 8 | const options = { waituntill: 'networkidle2' } 9 | const browser = await puppeteer.launch({ 10 | headless: false, 11 | }); 12 | const pages = await browser.pages(); 13 | const page = pages[0]; 14 | await page.goto('https://resi.id/lacak-resi-jnt', options); 15 | const res1 = await page.$('#input-single') 16 | await res1.type(nomer) 17 | await delay(1000) 18 | const selector = '#input-single-btn' 19 | await page.evaluate((selector) => document.querySelector(selector).click(), selector); 20 | await delay(3000) 21 | console.log('gud') 22 | if (page.url() == 'https://resi.id/lacak-resi-jnt' ){ 23 | console.log('manteb') 24 | }else{ 25 | console.log('gagal') 26 | }; 27 | console.log('selesai') 28 | await browser.close() 29 | })(); 30 | -------------------------------------------------------------------------------- /bissmillah.js: -------------------------------------------------------------------------------- 1 | # hackoktober 2 | # dapet kaos 3 | -------------------------------------------------------------------------------- /breakout/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 2D Breakout Game 6 | 7 | 8 | 9 |

0

10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /breakout/styles.css: -------------------------------------------------------------------------------- 1 | .grid { 2 | position: absolute; 3 | width: 560px; 4 | height: 300px; 5 | border: solid 1px black; 6 | margin-top: 100px; 7 | } 8 | 9 | .user { 10 | position: absolute; 11 | width: 100px; 12 | height: 20px; 13 | background-color: blueviolet; 14 | } 15 | 16 | .block { 17 | position: absolute; 18 | width: 100px; 19 | height: 20px; 20 | background-color: blue; 21 | } 22 | 23 | .ball { 24 | position: absolute; 25 | width: 20px; 26 | height: 20px; 27 | border-radius: 10px; 28 | background-color: red; 29 | } 30 | -------------------------------------------------------------------------------- /calculator.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | function toLower(inputText) { 4 | let lower = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 5 | let upper = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] 6 | let temp = ""; 7 | for (let i = 0; i < inputText.length; i++) { 8 | let isLower = true; 9 | for (let j = 0; j < upper.length; j++) { 10 | if (inputText.charAt(i) === upper[j]) { 11 | isLower = false; 12 | temp += lower[j]; 13 | } 14 | } 15 | if (isLower) { 16 | temp += inputText.charAt(i); 17 | } 18 | } 19 | return temp; 20 | } 21 | 22 | function isLetterArray(inputText) { 23 | let lower = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 24 | let text = toLower(inputText); 25 | for (let i = 0; i < lower.length; i++) { 26 | if (text[0] === lower[i]) { 27 | return true; 28 | } 29 | else { 30 | return false; 31 | } 32 | } 33 | return temp; 34 | } 35 | console.log(isLetterArray(9)) 36 | -------------------------------------------------------------------------------- /capitalFirstLetter.js: -------------------------------------------------------------------------------- 1 | const capitalFirstLetter = (word = '') => { 2 | const firstLetter = word.slice(0, 1).toLocaleUpperCase(); 3 | return `${firstLetter}${word.substring(1)}`; 4 | } 5 | 6 | console.log(capitalFirstLetter('hacktoberfest 2022')); -------------------------------------------------------------------------------- /change img to base64/index.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | const fs = require('fs'); 3 | 4 | async function processUrlImageToBase64(url) { 5 | return await axios(url, { responseType: 'arraybuffer' }).then(response => Buffer.from(response.data, 'binary').toString('base64')); 6 | } 7 | 8 | const imgUrl = 'https://asset-a.grid.id//crop/0x0:0x0/700x465/photo/2021/07/13/gambar-ilustrasi-bisa-memperjela-20210713123218.jpg' 9 | 10 | console.log(processUrlImageToBase64(imgUrl)); -------------------------------------------------------------------------------- /change img to base64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "change-image", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "node index.js" 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "axios": "^0.21.1" 15 | } 16 | } -------------------------------------------------------------------------------- /check-vowel-char.js: -------------------------------------------------------------------------------- 1 | function hitungAlphabet(str) { 2 | str = str.toUpperCase() 3 | const vokal = 'AIUEO'; 4 | const konsonan = 'BCDFGHJKLMNPQRSTVWXYZ'; 5 | const arrVokal =[]; 6 | const arrKonsonan=[]; 7 | for(let i =0;i new Promise((resolve, reject) => { 5 | fetch('https://revuto.com/api/v1/invitation/muhab3ea7c', { 6 | headers: { 7 | 'authority': 'revuto.com', 8 | 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"', 9 | 'accept': 'application/json, text/plain, */*', 10 | 'sec-ch-ua-mobile': '?1', 11 | 'user-agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36', 12 | 'sec-fetch-site': 'same-origin', 13 | 'sec-fetch-mode': 'cors', 14 | 'sec-fetch-dest': 'empty', 15 | 'referer': 'https://revuto.com/invite/muhab3ea7c', 16 | 'accept-language': 'en-US,en;q=0.9', 17 | 'cookie': '__cfduid=ddc3169ea6ed3f3a4c7aeb841abed85521620313025; _ga=GA1.2.2116285755.1620313027; _gid=GA1.2.1474259655.1620313027; _gat_UA-179206244-1=1' 18 | } 19 | }) 20 | .then(res => res.text()) 21 | .then(res => { 22 | const $ = cheerio.load(res); 23 | const data = 24 | resolve(res) 25 | }) 26 | .catch(err => reject(err)) 27 | }); 28 | 29 | (async () => { 30 | const getGet = await get(); 31 | console.log(getGet) 32 | 33 | })(); 34 | -------------------------------------------------------------------------------- /cnn.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | const cheerio = require('cheerio') 3 | 4 | const newsCnn = async(genre) => { 5 | const res = await axios.get(`https://www.cnnindonesia.com/${genre}`) 6 | const $ = cheerio.load(res.data) 7 | const hasil = [] 8 | $('article').each(function(a, b) { 9 | const link = $(b).find('a').attr('href') 10 | const thumb = $(b).find('img').attr('src') 11 | const judul = $(b).find('img').attr('alt') 12 | hasil.push({ judul, link, thumb }) 13 | }) 14 | return hasil 15 | } 16 | 17 | module.exports = { newsCnn } 18 | -------------------------------------------------------------------------------- /connectwallet.js: -------------------------------------------------------------------------------- 1 | import ethers from 'ethers'; 2 | 3 | const rpc = 'RPC' 4 | const mnemonic = 'MNEMONIC 12 WORDS' 5 | 6 | const app = express(); 7 | const provider = await new ethers.providers.WebSocketProvider(rpc) 8 | const wallet = await new ethers.Wallet.fromMnemonic(mnemonic); 9 | const account = await wallet.connect(provider); 10 | -------------------------------------------------------------------------------- /contact-app/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ -------------------------------------------------------------------------------- /contact-app/data/contacts.json: -------------------------------------------------------------------------------- 1 | [{"nama":"Lukman","email":"nulhakiml725@gmail.com","noHP":"081234567890"},{"nama":"Risqi Saputra","noHP":"08123123123"},{"nama":"Shakilla","email":"shakilla@gmail.com","noHP":"08123123123"}] -------------------------------------------------------------------------------- /contact-app/index.js: -------------------------------------------------------------------------------- 1 | const yargs = require("yargs"); 2 | const contacts = require("./contacts"); 3 | 4 | yargs 5 | .command({ 6 | command: "add", 7 | describe: "Menambahkan contact baru", 8 | builder: { 9 | nama: { 10 | describe: "Nama lengkap", 11 | demandOption: true, 12 | type: "string", 13 | }, 14 | email: { 15 | describe: "Email", 16 | demandOption: false, 17 | type: "string", 18 | }, 19 | noHP: { 20 | describe: "No Handphone", 21 | demandOption: true, 22 | type: "string", 23 | }, 24 | }, 25 | handler(argv) { 26 | contacts.save(argv.nama, argv.email, argv.noHP); 27 | }, 28 | }) 29 | .demandCommand(); 30 | 31 | // Menampilkan daftar semua nama& no hp contact 32 | yargs.command({ 33 | command: "list", 34 | describe: "Menampilkan semua nama dan no HP contact", 35 | handler() { 36 | contacts.listContact(); 37 | }, 38 | }); 39 | 40 | // Menampilkan detail kontak 41 | yargs.command({ 42 | command: "detail", 43 | describe: "Menampilkan detail kontak berdasarkan nama", 44 | builder: { 45 | nama: { 46 | describe: "Nama lengkap", 47 | demandOption: true, 48 | type: "string", 49 | }, 50 | }, 51 | handler(argv) { 52 | contacts.detailContact(argv.nama); 53 | }, 54 | }); 55 | 56 | // Menghapus kontak berdasarkan nama 57 | yargs.command({ 58 | command: "delete", 59 | describe: "Menghapus sebuah kontak berdasarkan nama", 60 | builder: { 61 | nama: { 62 | describe: "Nama lengkap", 63 | demandOption: true, 64 | type: "string", 65 | }, 66 | }, 67 | handler(argv) { 68 | contacts.deleteContact(argv.nama); 69 | }, 70 | }); 71 | 72 | yargs.parse(); 73 | -------------------------------------------------------------------------------- /contact-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "contact-app", 3 | "version": "1.0.0", 4 | "description": "Aplikasi Contact APP", 5 | "main": "index.js", 6 | "dependencies": { 7 | "chalk": "^4.1.0", 8 | "validator": "^13.5.2", 9 | "yargs": "^16.2.0" 10 | }, 11 | "devDependencies": {}, 12 | "scripts": { 13 | "test": "echo \"Error: no test specified\" && exit 1" 14 | }, 15 | "author": "Lukman", 16 | "license": "ISC" 17 | } 18 | -------------------------------------------------------------------------------- /convert-img-to-base64.js: -------------------------------------------------------------------------------- 1 | // import fileSystem from nodejs 2 | const fs = require('fs') 3 | 4 | // function to encode file data to base64 encoded string 5 | const base64Encodes = (file) => { 6 | // read binary data 7 | const bitmap = fs.readFileSync(file); 8 | // convert binary data to base64 encoded string 9 | return new Buffer(bitmap).toString('base64'); 10 | } 11 | 12 | // Usage || write img file in this project directory 13 | const base64strings = base64Encodes('exampleImage.png') 14 | 15 | // run node convert-img-to-base64.js in the terminal 16 | 17 | // Log base64 string 18 | console.log(base64strings) 19 | -------------------------------------------------------------------------------- /cors_by_yasas.js: -------------------------------------------------------------------------------- 1 | // CORS Function // 2 | const app = express(); 3 | 4 | app.use((req, res, next) => { 5 | res.setHeader("Access-Control-Allow-Origin", "*"), 6 | res.setHeader( 7 | "Access-Control-Allow-Methods", 8 | "GET,POST,PUT,DELETE,OPTIONS" 9 | ), 10 | res.setHeader( 11 | "Access-Control-Allow-Headers", 12 | "Content-Type, Authorization" 13 | ); 14 | next(); 15 | }); 16 | 17 | // Contributed by - Yasas Sandeepa 18 | // Undergraduate- University of Moratuwa 19 | // Sri Lanka -------------------------------------------------------------------------------- /create_server.js: -------------------------------------------------------------------------------- 1 | var http = require('http'); 2 | 3 | const createServer = async () => { 4 | await http 5 | .createServer(function (request, response) { 6 | response.writeHead(200, { 'Content-Type': 'text/plain' }); 7 | response.end('Hello my server'); 8 | }) 9 | .listen(3000); 10 | console.log('Server running at port 3000'); 11 | }; 12 | 13 | module.exports = { createServer }; 14 | -------------------------------------------------------------------------------- /e-commerce_scrapper/index.js: -------------------------------------------------------------------------------- 1 | const fetch = require('node-fetch'); 2 | const cheerio = require('cheerio'); 3 | 4 | const getProduct = () => new Promise((resolve,reject) => { 5 | fetch('https://basoaciakang.co.id/', { 6 | method: 'GET', 7 | headers: { 8 | 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Mobile Safari/537.36' 9 | } 10 | }) //pake promise 11 | 12 | 13 | .then (res => res.text()) 14 | .then(result => { 15 | const $ = cheerio.load(result); 16 | const menu = $('h4.title').text(); 17 | const desc = $('div.desc').text(); 18 | const topping = $('h4.title').text(); 19 | resolve("\t Berikut adalah Menu List : \n" + "\t\n\t" + menu + "\t\n\t" + desc + "\t\n\t" ) 20 | }) 21 | .catch(err => reject(err)) 22 | 23 | }); 24 | 25 | (async () => { 26 | const detailPrice = await getProduct() 27 | console.log(detailPrice) 28 | 29 | })(); 30 | -------------------------------------------------------------------------------- /ecommerce-store/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /ecommerce-store/README.md: -------------------------------------------------------------------------------- 1 | # ecommerce-store 2 | An full-stack eCommerce store web application in nodejs 3 | -------------------------------------------------------------------------------- /ecommerce-store/backend/app.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const PORT = process.env.PORT || 5000; 3 | const app = express(); 4 | require("./db"); 5 | const productRoute = require("./routes/product"); 6 | const authRoute = require("./routes/auth"); 7 | const path = require("path"); 8 | /************ MIDDLEVARES *************/ 9 | 10 | // Body parser middleware 11 | app.use(express.json()); 12 | app.use(express.urlencoded({ extended: true })); 13 | 14 | // Add headers in order to perform all operation on API 15 | // Because CORS Thing (Google it if you do not know) 16 | app.use((req, res, next) => { 17 | res.header("Access-Control-Allow-Origin", "*"); 18 | res.header("Access-Control-Allow-Header", "*"); 19 | 20 | next(); 21 | }); 22 | /************ ROUTES *************/ 23 | app.use("/api/v1/", productRoute); 24 | app.use("/api/v1/user", authRoute); 25 | 26 | if (process.env.NODE_ENV === "production") { 27 | app.use(express.static("../frontend/build")); 28 | 29 | app.get("*", (req, res) => { 30 | res.sendFile(path.join(__dirname, "../frontend", "build", "index.html")); 31 | }); 32 | } 33 | // listen to the port 34 | app.listen(PORT); 35 | -------------------------------------------------------------------------------- /ecommerce-store/backend/config/keys.js: -------------------------------------------------------------------------------- 1 | if (process.env.NODE_ENV === "production") { 2 | module.exports = require("./keys_prod"); 3 | } else { 4 | module.exports = require("./keys_dev"); 5 | } 6 | -------------------------------------------------------------------------------- /ecommerce-store/backend/config/keys_dev.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | mongoURI: 3 | "mongodb+srv://ajay:ajay@cluster0-fhjlv.mongodb.net/ecommerce-shop?retryWrites=true&w=majority", 4 | secretOrKey: "secret_key", 5 | }; 6 | -------------------------------------------------------------------------------- /ecommerce-store/backend/config/keys_prod.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | mongoURI: process.env.MONGO_URI, 3 | secretOrKey: process.env.SECRET_OR_KEY, 4 | }; 5 | -------------------------------------------------------------------------------- /ecommerce-store/backend/db.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | require("dotenv/config"); 3 | 4 | return mongoose.connect( 5 | process.env.DB_CONNECTION, 6 | { useNewUrlParser: true, useUnifiedTopology: true }, 7 | () => console.log("conected to db") 8 | ); 9 | -------------------------------------------------------------------------------- /ecommerce-store/backend/model/CatModal.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | const Schema = mongoose.Schema; 3 | 4 | // Create Schema 5 | const CategorySchema = new Schema({ 6 | id: { 7 | type: Schema.Types.ObjectId, 8 | }, 9 | name: { 10 | type: String, 11 | required: true, 12 | }, 13 | }); 14 | 15 | module.exports = Category = mongoose.model("category", CategorySchema); 16 | -------------------------------------------------------------------------------- /ecommerce-store/backend/model/ProductModal.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | const Schema = mongoose.Schema; 3 | 4 | // Create Schema 5 | const ProductSchema = new Schema({ 6 | id: { 7 | type: Schema.Types.ObjectId, 8 | }, 9 | title: { 10 | type: String, 11 | required: true, 12 | }, 13 | routeName: { 14 | type: String, 15 | required: true, 16 | max: 40, 17 | }, 18 | items: [ 19 | { 20 | product_id: { 21 | type: Schema.Types.ObjectId, 22 | }, 23 | name: { 24 | type: String, 25 | required: true, 26 | }, 27 | imageUrl: { 28 | type: String, 29 | required: true, 30 | }, 31 | price: { 32 | type: String, 33 | }, 34 | }, 35 | ], 36 | }); 37 | 38 | module.exports = Product = mongoose.model("product", ProductSchema); 39 | -------------------------------------------------------------------------------- /ecommerce-store/backend/model/User.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | 3 | const Schema = mongoose.Schema; 4 | 5 | //create Schema 6 | const UserSchema = new Schema({ 7 | name: { 8 | type: String, 9 | required: true, 10 | }, 11 | email: { 12 | type: String, 13 | required: true, 14 | }, 15 | password: { 16 | type: String, 17 | required: true, 18 | }, 19 | date: { 20 | type: Date, 21 | default: Date.now, 22 | }, 23 | }); 24 | 25 | module.exports = User = mongoose.model("users", UserSchema); 26 | -------------------------------------------------------------------------------- /ecommerce-store/backend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "backend", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "node app.js", 8 | "server": "nodemon server.js", 9 | "client-install": "npm install --prefix ../frontend", 10 | "client": "npm start --prefix ../frontend", 11 | "dev": "concurrently \"npm run server\" \"npm run client\"", 12 | "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix ../frontend && npm run build --prefix ../frontend" 13 | }, 14 | "keywords": [], 15 | "author": "", 16 | "license": "ISC", 17 | "dependencies": { 18 | "@hapi/joi": "^17.1.1", 19 | "bcryptjs": "^2.4.3", 20 | "dotenv": "^8.2.0", 21 | "express": "^4.17.1", 22 | "jsonwebtoken": "^8.5.1", 23 | "mongoose": "^5.9.18", 24 | "nodemon": "^2.0.4" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ecommerce-store/backend/routes/auth.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | const User = require("../model/User"); 4 | const bcrypt = require("bcryptjs"); 5 | const jwt = require("jsonwebtoken"); 6 | const { registerValidation, loginValidation } = require("../validation"); 7 | router.post("/register", async (req, res) => { 8 | const { error } = registerValidation(req.body); 9 | // console.log(req.body); 10 | 11 | if (error) { 12 | return res.status(400).send(error.details[0].message); 13 | } 14 | 15 | const isUserExist = await User.findOne({ email: req.body.email }); 16 | if (isUserExist) { 17 | return res.status(400).send("user exist"); 18 | } 19 | 20 | const salt = await bcrypt.genSalt(10); 21 | const hashPassword = await bcrypt.hash(req.body.password, salt); 22 | const newUser = { 23 | name: req.body.name, 24 | email: req.body.email, 25 | password: hashPassword, 26 | }; 27 | 28 | const user = new User(newUser); 29 | 30 | try { 31 | await user.save(); 32 | res.status(200).send({ user: user._id }); 33 | } catch (error) { 34 | res.status(400).send(error); 35 | } 36 | }); 37 | 38 | router.post("/login", async (req, res) => { 39 | const { error } = loginValidation(req.body); 40 | if (error) { 41 | return res.status(400).send(error.details[0].message); 42 | } 43 | const isUserExist = await User.findOne({ email: req.body.email }); 44 | 45 | if (!isUserExist) { 46 | return res.status(400).send({ msg: "user does not exist" }); 47 | } 48 | 49 | //password is correct 50 | const validPass = await bcrypt.compare( 51 | req.body.password, 52 | isUserExist.password 53 | ); 54 | if (!validPass) { 55 | return res.status(400).send("email or password wrong"); 56 | } 57 | 58 | // create token 59 | const token = jwt.sign({ _id: isUserExist._id }, process.env.SECRET_KEY); 60 | res.header("auth-token", token).send({ token, user: isUserExist }); 61 | }); 62 | module.exports = router; 63 | -------------------------------------------------------------------------------- /ecommerce-store/backend/routes/cat.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kokonior/NodeJS-Projects/94383782aa273c162d2aa7d315ba22e1dcf2ec48/ecommerce-store/backend/routes/cat.js -------------------------------------------------------------------------------- /ecommerce-store/backend/routes/product.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const router = express.Router(); 3 | 4 | const mongoose = require("mongoose"); 5 | const Product = require("../model/ProductModal"); 6 | const Category = require("../model/CatModal"); 7 | 8 | // Get all products 9 | router.get("/product", (req, res) => { 10 | Product.find() 11 | .then((products) => res.json([])) 12 | .catch((err) => 13 | res.status(404).json({ 14 | nopostsfound: "No product found", 15 | }) 16 | ); 17 | }); 18 | 19 | // Get all category name 20 | router.get("/category", (req, res) => { 21 | Category.find() 22 | .then((category) => res.json([])) 23 | .catch((err) => 24 | res.status(404).json({ 25 | nocatsfound: "No Category found", 26 | }) 27 | ); 28 | }); 29 | 30 | // Get all product by specific category name 31 | router.get("/product/:cat_name", (req, res) => { 32 | Product.find({ routeName: req.params["cat_name"] }) 33 | .then((product) => res.json(product)) 34 | .catch((err) => 35 | res.status(404).json({ 36 | nocatsfound: "No product found", 37 | }) 38 | ); 39 | }); 40 | 41 | module.exports = router; 42 | -------------------------------------------------------------------------------- /ecommerce-store/backend/validation.js: -------------------------------------------------------------------------------- 1 | const Joi = require("@hapi/joi"); 2 | const registerValidation = (data) => { 3 | const schema = Joi.object({ 4 | name: Joi.string().min(6).required(), 5 | email: Joi.string().min(6).required().email(), 6 | password: Joi.string().min(6).required(), 7 | }); 8 | return schema.validate(data); 9 | }; 10 | 11 | const loginValidation = (data) => { 12 | const schema = Joi.object({ 13 | email: Joi.string().min(6).required().email(), 14 | password: Joi.string().min(6).required(), 15 | }); 16 | return schema.validate(data); 17 | }; 18 | 19 | module.exports.registerValidation = registerValidation; 20 | module.exports.loginValidation = loginValidation; 21 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.5.0", 8 | "@testing-library/user-event": "^7.2.1", 9 | "axios": "^0.19.2", 10 | "jwt-decode": "^2.2.0", 11 | "node-sass": "^4.14.1", 12 | "react": "^16.13.1", 13 | "react-dom": "^16.13.1", 14 | "react-redux": "^7.2.0", 15 | "react-router-dom": "^5.2.0", 16 | "react-scripts": "3.4.1", 17 | "redux": "^4.0.5", 18 | "redux-logger": "^3.0.6", 19 | "redux-thunk": "^2.3.0" 20 | }, 21 | "proxy": "http://localhost:5000", 22 | "scripts": { 23 | "start": "react-scripts start", 24 | "build": "react-scripts build", 25 | "test": "react-scripts test", 26 | "eject": "react-scripts eject" 27 | }, 28 | "eslintConfig": { 29 | "extends": "react-app" 30 | }, 31 | "browserslist": { 32 | "production": [ 33 | ">0.2%", 34 | "not dead", 35 | "not op_mini all" 36 | ], 37 | "development": [ 38 | "last 1 chrome version", 39 | "last 1 firefox version", 40 | "last 1 safari version" 41 | ] 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kokonior/NodeJS-Projects/94383782aa273c162d2aa7d315ba22e1dcf2ec48/ecommerce-store/frontend/public/favicon.ico -------------------------------------------------------------------------------- /ecommerce-store/frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 21 | 22 | 23 | 32 | Ecommerce-Shop 33 | 34 | 35 | 36 |
37 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kokonior/NodeJS-Projects/94383782aa273c162d2aa7d315ba22e1dcf2ec48/ecommerce-store/frontend/public/logo192.png -------------------------------------------------------------------------------- /ecommerce-store/frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kokonior/NodeJS-Projects/94383782aa273c162d2aa7d315ba22e1dcf2ec48/ecommerce-store/frontend/public/logo512.png -------------------------------------------------------------------------------- /ecommerce-store/frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | display: flex; 3 | flex-direction: column; 4 | min-height: 100%; 5 | justify-content: space-between; 6 | } 7 | 8 | .main { 9 | height: 100%; 10 | } 11 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./App.css"; 3 | import jwt_decode from "jwt-decode"; 4 | import { setCurrentUser } from "./redux/user/user.actions"; 5 | import store from "./redux/store"; 6 | import { Switch, Route } from "react-router-dom"; 7 | import MainNavigation from "./components/navigation/mainNavigation.component"; 8 | import Footer from "./components/footer/footer.component"; 9 | import HomePage from "./pages/homePage/homePage"; 10 | import ShopPage from "./pages/shopPage/shopPage"; 11 | import SignInAndSignUpPage from "./pages/sign-in-and-sign-up/sign-in-and-sign-up.component"; 12 | import CheckoutPage from "./pages/checkout/checkout.component"; 13 | import PrivateRoute from "./Private-route"; 14 | if (localStorage.jwtToken) { 15 | // set auth tioken 16 | // setAuthToken(localStorage.jwtToken); 17 | // decode token 18 | const decoded = jwt_decode(localStorage.jwtToken); 19 | store.dispatch(setCurrentUser(decoded)); 20 | } 21 | 22 | function App() { 23 | return ( 24 |
25 | 26 |
27 | 28 | 29 | 30 | 31 | 32 | 33 |
34 | 35 |
36 |
37 | ); 38 | } 39 | 40 | export default App; 41 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/Private-route.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Route, Redirect } from "react-router-dom"; 3 | import { connect } from "react-redux"; 4 | const PrivateRoute = ({ component: Component, auth, ...rest }) => ( 5 | 8 | auth ? : 9 | } 10 | /> 11 | ); 12 | 13 | const mapStateToProps = (state) => ({ 14 | auth: state.user.currentUser, 15 | }); 16 | 17 | export default connect(mapStateToProps)(PrivateRoute); 18 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/assets/crown.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Group 5 | Created with Sketch. 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/assets/shopping-bag.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 8 | 12 | 16 | 19 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/cart-dropdown/cart-dropdown.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./cart-dropdown.styles.scss"; 3 | import CartItem from "../cart-item/cart-item.component"; 4 | import CustomButton from "../custom-button/custom-button.component"; 5 | import { withRouter } from "react-router-dom"; 6 | import { connect } from "react-redux"; 7 | const CartDropdown = ({ cartItems, history, toggleCart }) => ( 8 |
9 |
10 | {cartItems && cartItems.length ? ( 11 | cartItems.map((cartItem) => ( 12 | 13 | )) 14 | ) : ( 15 | Your Cart Is Empty 16 | )} 17 |
18 | { 20 | history.push("/checkout"); 21 | toggleCart(); 22 | }} 23 | > 24 | GO TO CHECKOUT{" "} 25 | 26 |
27 | ); 28 | 29 | const mapStateToProps = (state) => ({ 30 | cartItems: state.cart.cartItems, 31 | }); 32 | 33 | export default connect(mapStateToProps)(withRouter(CartDropdown)); 34 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/cart-dropdown/cart-dropdown.styles.scss: -------------------------------------------------------------------------------- 1 | .cart-dropdown { 2 | position: absolute; 3 | width: 240px; 4 | height: 340px; 5 | display: flex; 6 | flex-direction: column; 7 | padding: 20px; 8 | border: 1px solid black; 9 | background-color: white; 10 | top: 90px; 11 | right: 40px; 12 | z-index: 5; 13 | 14 | .empty-message { 15 | font-size: 18px; 16 | margin: 50px auto; 17 | } 18 | .cart-items { 19 | height: 240px; 20 | display: flex; 21 | flex-direction: column; 22 | overflow: scroll; 23 | } 24 | 25 | button { 26 | margin-top: auto; 27 | font-size: 1.2rem; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/cart-icon/cart-icon.component.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import "./cart-icon.styles.scss"; 3 | import { selectCartItemsCount } from "../../redux/cart/cart.selectors"; 4 | import { connect } from "react-redux"; 5 | import { ReactComponent as ShoppingIcon } from "../../assets/shopping-bag.svg"; 6 | class CartIcon extends Component { 7 | render() { 8 | const { toggleCartHidden, cartItemsCount } = this.props; 9 | return ( 10 |
11 | 12 | {cartItemsCount} 13 |
14 | ); 15 | } 16 | } 17 | 18 | const mapStateToProps = (state) => ({ 19 | cartItemsCount: selectCartItemsCount(state.cart.cartItems), 20 | }); 21 | 22 | export default connect(mapStateToProps)(CartIcon); 23 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/cart-icon/cart-icon.styles.scss: -------------------------------------------------------------------------------- 1 | .cart-icon { 2 | width: 45px; 3 | height: 45px; 4 | position: relative; 5 | display: flex; 6 | align-items: center; 7 | justify-content: center; 8 | cursor: pointer; 9 | 10 | .shopping-icon { 11 | width: 24px; 12 | height: 24px; 13 | } 14 | 15 | .item-count { 16 | position: absolute; 17 | font-size: 10px; 18 | font-weight: bold; 19 | bottom: 12px; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/cart-item/cart-item.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./cart-item.styles.scss"; 3 | 4 | const CartItem = ({ item: { imageUrl, price, name, quantity } }) => ( 5 |
6 | item 7 |
8 | {name} 9 | 10 | {quantity} X ${price} 11 | 12 |
13 |
14 | ); 15 | 16 | export default CartItem; 17 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/cart-item/cart-item.styles.scss: -------------------------------------------------------------------------------- 1 | .cart-item { 2 | width: 100%; 3 | display: flex; 4 | height: 80px; 5 | margin-bottom: 15px; 6 | 7 | img { 8 | width: 30%; 9 | } 10 | 11 | .item-details { 12 | width: 70%; 13 | display: flex; 14 | flex-direction: column; 15 | align-items: flex-start; 16 | justify-content: center; 17 | padding: 10px 20px; 18 | 19 | .name { 20 | font-size: 16px; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/category/cat_data.js: -------------------------------------------------------------------------------- 1 | export const CAT_NAMES = ["mens", "womens", "sneakers", "jackets", "hats"]; 2 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/category/category.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./category.styles.scss"; 3 | import { Link } from "react-router-dom"; 4 | import { CAT_NAMES } from "./cat_data"; 5 | import { connect } from "react-redux"; 6 | import { getProductByCategory } from "../../redux/producs/products.action"; 7 | function CategoryItem(props) { 8 | const categories = CAT_NAMES; 9 | return ( 10 |
11 |

Category

12 | 24 |
25 | ); 26 | } 27 | 28 | export default connect(null, { getProductByCategory })(CategoryItem); 29 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/category/category.styles.scss: -------------------------------------------------------------------------------- 1 | .category { 2 | display: flex; 3 | flex-direction: column; 4 | &__item { 5 | display: flex; 6 | flex-direction: column; 7 | 8 | &--link { 9 | text-decoration: none; 10 | font-size: 1.8rem; 11 | font-weight: 400; 12 | text-transform: uppercase; 13 | color: #000; 14 | &:hover { 15 | background-color: rgb(161, 25, 25); 16 | } 17 | &:focus { 18 | background-color: rgb(161, 25, 25); 19 | } 20 | &:active { 21 | background-color: rgb(161, 25, 25); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/checkout-item/checkout-item.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./checkout-item.styles.scss"; 3 | import { connect } from "react-redux"; 4 | import { 5 | clearItemFromCart, 6 | addItem, 7 | removeItem, 8 | } from "../../redux/cart/cart.action"; 9 | const CheckoutItem = ({ cartItem, clearItem, addItem, removeItem }) => { 10 | const { imageUrl, price, name, quantity } = cartItem; 11 | return ( 12 |
13 |
14 | item 15 |
16 | {name} 17 | 18 |
removeItem(cartItem)}> 19 | ❮ 20 |
21 | {quantity} 22 |
addItem(cartItem)}> 23 | ❯ 24 |
25 |
26 | 27 | $ {price} 28 |
clearItem(cartItem)}> 29 | ✕ 30 |
31 |
32 | ); 33 | }; 34 | 35 | const mapDispatchToProps = (dispatch) => ({ 36 | clearItem: (item) => dispatch(clearItemFromCart(item)), 37 | addItem: (item) => dispatch(addItem(item)), 38 | removeItem: (item) => dispatch(removeItem(item)), 39 | }); 40 | export default connect(null, mapDispatchToProps)(CheckoutItem); 41 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/checkout-item/checkout-item.styles.scss: -------------------------------------------------------------------------------- 1 | .checkout-item { 2 | width: 100%; 3 | display: flex; 4 | min-height: 100px; 5 | border-bottom: 1px solid darkgrey; 6 | padding: 15px 0; 7 | font-size: 20px; 8 | align-items: center; 9 | 10 | .image-container { 11 | width: 23%; 12 | padding-right: 15px; 13 | 14 | img { 15 | width: 100%; 16 | height: 100%; 17 | } 18 | } 19 | .name, 20 | .quantity, 21 | .price { 22 | width: 23%; 23 | } 24 | 25 | .quantity { 26 | padding-left: 20px; 27 | display: flex; 28 | align-items: center; 29 | 30 | .arrow{ 31 | cursor: pointer; 32 | } 33 | .value{ 34 | margin: 0 10px; 35 | } 36 | } 37 | 38 | .remove-button { 39 | padding-left: 12px; 40 | cursor: pointer; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/custom-button/custom-button.component.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import './custom-button.styles.scss'; 3 | export default function CustomButton({ children, isGoogleSignIn, inverted, ...otherProps }) { 4 | return ( 5 | 8 | ); 9 | } 10 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/custom-button/custom-button.styles.scss: -------------------------------------------------------------------------------- 1 | .custom-button { 2 | min-width: 165px; 3 | width: auto; 4 | height: 50px; 5 | letter-spacing: 0.5px; 6 | line-height: 50px; 7 | padding: 0 35px 0 35px; 8 | font-size: 15px; 9 | background-color: black; 10 | color: white; 11 | text-transform: uppercase; 12 | font-family: 'Open Sans Condensed'; 13 | font-weight: bolder; 14 | border: none; 15 | cursor: pointer; 16 | display: flex; 17 | justify-content: center; 18 | 19 | &:hover { 20 | background-color: white; 21 | color: black; 22 | border: 1px solid black; 23 | } 24 | 25 | &.google-sign-in { 26 | background-color: #4285f4; 27 | color: white; 28 | 29 | &:hover { 30 | background-color: #357ae8; 31 | border: none; 32 | } 33 | } 34 | 35 | &.inverted { 36 | background-color: white; 37 | color: black; 38 | border: 1px solid black; 39 | 40 | &:hover { 41 | background-color: black; 42 | color: white; 43 | border: none; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/directory-item/directoryItem.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./directoryItem.styles.scss"; 3 | import { withRouter } from "react-router-dom"; 4 | 5 | function DirectoryItem(props) { 6 | const { title, imageUrl, linkUrl } = props.item; 7 | // console.log(props); 8 | 9 | return ( 10 |
props.history.push(`/${linkUrl}`)} 13 | > 14 |
18 | 24 |
25 | ); 26 | } 27 | 28 | export default withRouter(DirectoryItem); 29 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/directory-item/directoryItem.styles.scss: -------------------------------------------------------------------------------- 1 | .directory-item { 2 | min-width: 30rem; 3 | height: 240px; 4 | flex: 1 1 auto; 5 | display: flex; 6 | align-items: center; 7 | // flex-direction: column; 8 | cursor: pointer; 9 | justify-content: center; 10 | border: 1px solid black; 11 | position: relative; 12 | margin: 0 7.5px 15px; 13 | &--image { 14 | width: 100%; 15 | height: 100%; 16 | object-fit: cover; 17 | background-position: center; 18 | } 19 | &--title { 20 | font-size: 1.8rem; 21 | font-weight: 400; 22 | position: absolute; 23 | background: #000; 24 | padding: 1rem 1rem; 25 | cursor: pointer; 26 | text-transform: uppercase; 27 | &:hover { 28 | background-color: rgb(65, 61, 61); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/directory/directory-data.js: -------------------------------------------------------------------------------- 1 | const sections = [ 2 | { 3 | title: "hats", 4 | imageUrl: "https://i.ibb.co/cvpntL1/hats.png", 5 | id: 1, 6 | linkUrl: "shop/hats", 7 | }, 8 | { 9 | title: "jackets", 10 | imageUrl: "https://i.ibb.co/px2tCc3/jackets.png", 11 | id: 2, 12 | linkUrl: "shop/jackets", 13 | }, 14 | { 15 | title: "sneakers", 16 | imageUrl: "https://i.ibb.co/0jqHpnp/sneakers.png", 17 | id: 3, 18 | linkUrl: "shop/sneakers", 19 | }, 20 | { 21 | title: "womens", 22 | imageUrl: "https://i.ibb.co/GCCdy8t/womens.png", 23 | size: "large", 24 | id: 4, 25 | linkUrl: "shop/womens", 26 | }, 27 | { 28 | title: "mens", 29 | imageUrl: "https://i.ibb.co/R70vBrQ/men.png", 30 | size: "large", 31 | id: 5, 32 | linkUrl: "shop/mens", 33 | }, 34 | ]; 35 | 36 | export default sections; 37 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/directory/directory.component.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import "./directory.styles.scss"; 3 | import DirectoryItem from "../directory-item/directoryItem.component"; 4 | import sections from "./directory-data"; 5 | class Directory extends Component { 6 | constructor() { 7 | super(); 8 | this.state = { 9 | Directory: sections, 10 | }; 11 | } 12 | 13 | render() { 14 | return ( 15 | 16 |
17 | {this.state.Directory.map((item) => ( 18 | 19 | ))} 20 |
21 |
22 | ); 23 | } 24 | } 25 | 26 | export default Directory; 27 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/directory/directory.styles.scss: -------------------------------------------------------------------------------- 1 | .dircetory { 2 | width: 100%; 3 | display: flex; 4 | flex-wrap: wrap; 5 | justify-content: space-between; 6 | padding: 2rem 2rem; 7 | } 8 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/footer/footer.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./footer.styles.scss"; 3 | export default function Footer() { 4 | return ( 5 |
6 |

7 | Copyrights © 2020 . design by{" "} 8 | Ajay 9 |

10 |
11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/footer/footer.styles.scss: -------------------------------------------------------------------------------- 1 | footer { 2 | font-size: 2rem; 3 | background-color: #000000; 4 | color: #fff; 5 | display: flex; 6 | 7 | justify-content: center; 8 | margin-top: 2rem; 9 | } 10 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/form-input/form-input.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | import "./form-input.styles.scss"; 4 | 5 | const FormInput = ({ handleChange, label, ...otherProps }) => ( 6 |
7 | 8 | {label ? ( 9 | 16 | ) : null} 17 |
18 | ); 19 | 20 | export default FormInput; 21 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/form-input/form-input.styles.scss: -------------------------------------------------------------------------------- 1 | $sub-color: grey; 2 | $main-color: black; 3 | 4 | @mixin shrinkLabel { 5 | top: -14px; 6 | font-size: 12px; 7 | color: $main-color; 8 | } 9 | 10 | .group { 11 | position: relative; 12 | margin: 45px 0; 13 | 14 | .form-input { 15 | background: none; 16 | background-color: white; 17 | color: $sub-color; 18 | font-size: 18px; 19 | padding: 10px 10px 10px 5px; 20 | display: block; 21 | width: 100%; 22 | border: none; 23 | border-radius: 0; 24 | border-bottom: 1px solid $sub-color; 25 | margin: 25px 0; 26 | 27 | &:focus { 28 | outline: none; 29 | } 30 | 31 | &:focus ~ .form-input-label { 32 | @include shrinkLabel(); 33 | } 34 | } 35 | 36 | input[type='password'] { 37 | letter-spacing: 0.3em; 38 | } 39 | 40 | .form-input-label { 41 | color: $sub-color; 42 | font-size: 16px; 43 | font-weight: normal; 44 | position: absolute; 45 | pointer-events: none; 46 | left: 5px; 47 | top: 10px; 48 | transition: 300ms ease all; 49 | 50 | &.shrink { 51 | @include shrinkLabel(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/navLinks/navLink.component.jsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kokonior/NodeJS-Projects/94383782aa273c162d2aa7d315ba22e1dcf2ec48/ecommerce-store/frontend/src/components/navLinks/navLink.component.jsx -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/navigation/mainNavigation.component.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import "./mainNavigation.styles.scss"; 3 | import { ReactComponent as Logo } from "../../assets/crown.svg"; 4 | import { Link } from "react-router-dom"; 5 | import CartDropdown from "../cart-dropdown/cart-dropdown.component"; 6 | import { connect } from "react-redux"; 7 | import { logoutUser } from "../../redux/user/user.actions"; 8 | import CartIcon from "../cart-icon/cart-icon.component"; 9 | class MainNavigation extends Component { 10 | constructor() { 11 | super(); 12 | this.state = { 13 | toggleCart: false, 14 | }; 15 | } 16 | toggleCartHidden = () => { 17 | this.setState({ toggleCart: !this.state.toggleCart }); 18 | }; 19 | render() { 20 | const { currentUser } = this.props; 21 | return ( 22 | 59 | ); 60 | } 61 | } 62 | 63 | const mapStateToProps = (state) => ({ 64 | currentUser: state.user.currentUser, 65 | }); 66 | export default connect(mapStateToProps, { logoutUser })(MainNavigation); 67 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/navigation/mainNavigation.styles.scss: -------------------------------------------------------------------------------- 1 | .header { 2 | height: 8rem; 3 | margin: 0 4rem; 4 | display: flex; 5 | justify-content: space-between; 6 | align-items: center; 7 | margin-bottom: 5rem; 8 | // padding: 1.5rem; 9 | &__logo { 10 | height: 100%; 11 | } 12 | 13 | &__nav { 14 | width: 50%; 15 | display: flex; 16 | list-style: none; 17 | align-items: center; 18 | justify-content: space-between; 19 | 20 | &--item { 21 | &-link { 22 | text-decoration: none; 23 | color: #000; 24 | font-size: 1.8rem; 25 | font-weight: 300; 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/shop-item-card/shopItemCard.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./shopItemCard.styles.scss"; 3 | import CustomButton from "../custom-button/custom-button.component"; 4 | import { connect } from "react-redux"; 5 | import { addItem } from "../../redux/cart/cart.action"; 6 | const ShopItemCard = ({ item, addItem }) => { 7 | const { name, imageUrl, price } = item; 8 | return ( 9 |
10 |
17 |
18 | {name} 19 | {price} 20 |
21 | addItem(item)}> 22 | Add To Cart 23 | 24 |
25 | ); 26 | }; 27 | 28 | export default connect(null, { addItem })(ShopItemCard); 29 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/shop-item-card/shopItemCard.styles.scss: -------------------------------------------------------------------------------- 1 | .collection-item { 2 | width: 22vw; 3 | display: flex; 4 | flex-direction: column; 5 | height: 350px; 6 | align-items: center; 7 | position: relative; 8 | 9 | .image { 10 | width: 100%; 11 | height: 95%; 12 | background-size: cover; 13 | background-position: center; 14 | margin-bottom: 5px; 15 | } 16 | 17 | .custom-button { 18 | width: 80%; 19 | opacity: 0.7; 20 | position: absolute; 21 | top: 255px; 22 | display: none; 23 | } 24 | 25 | &:hover { 26 | .image { 27 | opacity: 0.8; 28 | } 29 | 30 | .custom-button { 31 | opacity: 0.85; 32 | display: flex; 33 | } 34 | } 35 | 36 | .collection-footer { 37 | width: 100%; 38 | height: 5%; 39 | display: flex; 40 | justify-content: space-between; 41 | font-size: 18px; 42 | 43 | .name { 44 | width: 90%; 45 | margin-bottom: 15px; 46 | } 47 | 48 | .price { 49 | width: 10%; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/shop-items/shop-items.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./shop-items.styles.scss"; 3 | import ShopItemCard from "../shop-item-card/shopItemCard.component"; 4 | import { connect } from "react-redux"; 5 | const ShopItem = ({ product }) => { 6 | return ( 7 |
8 | {product && 9 | product.items.map((item) => ( 10 | 11 | ))} 12 |
13 | ); 14 | }; 15 | 16 | const mapStateToProps = (state) => ({ 17 | product: state.products.product[0], 18 | }); 19 | 20 | export default connect(mapStateToProps)(ShopItem); 21 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/shop-items/shop-items.styles.scss: -------------------------------------------------------------------------------- 1 | .products { 2 | width: 100%; 3 | display: grid; 4 | // flex-wrap: wrap; 5 | // justify-content: space-between; 6 | align-items: center; 7 | grid-template-columns: repeat(auto-fill, minmax(22vw, 1fr)); 8 | grid-row-gap: 2rem; 9 | } 10 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/sign-in/sign-in.component.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import "./sign-in.styles.scss"; 3 | import FormInput from "../form-input/form-input.component"; 4 | import CustomButton from "../custom-button/custom-button.component"; 5 | import { connect } from "react-redux"; 6 | import { loginUser } from "../../redux/user/user.actions"; 7 | import { withRouter } from "react-router-dom"; 8 | class SignIn extends Component { 9 | constructor(props) { 10 | super(props); 11 | 12 | this.state = { 13 | email: "", 14 | password: "", 15 | }; 16 | } 17 | 18 | handleChange = (e) => { 19 | const { value, name } = e.target; 20 | this.setState({ [name]: value }); 21 | }; 22 | 23 | handleSubmit = async (event) => { 24 | this.props.loginUser(this.state, this.props.history); 25 | 26 | event.preventDefault(); 27 | }; 28 | render() { 29 | return ( 30 |
31 |

I already have an account

32 | Sign in with your email and password 33 | 34 |
35 | 43 | 44 | 52 | 53 |
54 | SIGN IN 55 | 56 | 57 | {""} 58 | SIGN IN With Google{""} 59 | 60 |
61 | 62 |
63 | ); 64 | } 65 | } 66 | 67 | export default connect(null, { loginUser })(withRouter(SignIn)); 68 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/sign-in/sign-in.styles.scss: -------------------------------------------------------------------------------- 1 | .sign-in{ 2 | width:380px; 3 | display: flex; 4 | flex-direction: column; 5 | 6 | .title{ 7 | margin: 10px 0; 8 | } 9 | .buttons{ 10 | display: flex; 11 | justify-content:space-between ; 12 | } 13 | } -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/sign-up/sign-up.styles.scss: -------------------------------------------------------------------------------- 1 | .sign-up { 2 | display: flex; 3 | flex-direction: column; 4 | width: 380px; 5 | 6 | .title { 7 | margin: 10px 0; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/stripe-button/stripe-button.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import StripeCheckout from "react-stripe-checkout"; 3 | 4 | const StripeCheckoutButton = ({ price }) => { 5 | const priceForStripe = price * 100; 6 | const publishableKey = "pk_test_wxEZzRIQDkcWA9MRtfMttZye00dnSV1Drg"; 7 | 8 | const onToken = (token) => { 9 | console.log(token); 10 | alert("Payment Succesful"); 11 | }; 12 | return ( 13 | 25 | ); 26 | }; 27 | 28 | export default StripeCheckoutButton; 29 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/components/stripe-button/stripe-button.styles.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kokonior/NodeJS-Projects/94383782aa273c162d2aa7d315ba22e1dcf2ec48/ecommerce-store/frontend/src/components/stripe-button/stripe-button.styles.scss -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/index.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | box-sizing: border-box; 5 | } 6 | html { 7 | font-size: 62.5%; 8 | } 9 | body { 10 | font-family: "Open Sans", sans-serif; 11 | font-size: 1.6rem; 12 | font-weight: 400; 13 | padding: 1rem; 14 | line-height: 1.7; 15 | -webkit-font-smoothing: antialiased; 16 | -moz-osx-font-smoothing: grayscale; 17 | } 18 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import "./index.css"; 4 | import App from "./App"; 5 | import * as serviceWorker from "./serviceWorker"; 6 | import { BrowserRouter } from "react-router-dom"; 7 | import { Provider } from "react-redux"; 8 | import store from "./redux/store"; 9 | ReactDOM.render( 10 | 11 | 12 | 13 | 14 | 15 | 16 | , 17 | document.getElementById("root") 18 | ); 19 | 20 | // If you want your app to work offline and load faster, you can change 21 | // unregister() to register() below. Note this comes with some pitfalls. 22 | // Learn more about service workers: https://bit.ly/CRA-PWA 23 | serviceWorker.unregister(); 24 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/pages/checkout/checkout.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./checkout.styles.scss"; 3 | import CheckoutItem from "../../components/checkout-item/checkout-item.component"; 4 | // import StripeCheckoutButton from "../../components/stripe-button/stripe-button.component"; 5 | import { connect } from "react-redux"; 6 | import { selectCartTotal } from "../../redux/cart/cart.selectors"; 7 | 8 | const CheckoutPage = ({ cartItems, total }) => ( 9 |
10 |
11 |
12 | Product 13 |
14 | 15 |
16 | Description 17 |
18 | 19 |
20 | Quantity 21 |
22 | 23 |
24 | Price 25 |
26 | 27 |
28 | Remove 29 |
30 |
31 | {cartItems && 32 | cartItems.map((cartItem) => ( 33 | 34 | ))} 35 | 36 |
37 | TOTAL : ${total} 38 |
39 | 40 | {/* */} 41 |
42 | ); 43 | 44 | const mapStateToProps = (state) => ({ 45 | cartItems: state.cart.cartItems, 46 | total: selectCartTotal(state.cart.cartItems), 47 | }); 48 | 49 | export default connect(mapStateToProps)(CheckoutPage); 50 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/pages/checkout/checkout.styles.scss: -------------------------------------------------------------------------------- 1 | .checkout-page { 2 | width: 55%; 3 | min-height: 90vh; 4 | display: flex; 5 | flex-direction: column; 6 | align-items: center; 7 | margin: 50px auto 0; 8 | 9 | .checkout-header { 10 | width: 100%; 11 | padding: 10px 0; 12 | display: flex; 13 | justify-content: space-between; 14 | border-bottom: 1px solid darkgrey; 15 | 16 | .header-block { 17 | text-transform: capitalize; 18 | width: 23%; 19 | 20 | &:last-child { 21 | width: 8%; 22 | } 23 | } 24 | } 25 | 26 | .total { 27 | margin-top: 30px; 28 | margin-left: auto; 29 | font-size: 36px; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/pages/homePage/homePage.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Directory from "../../components/directory/directory.component"; 3 | export default function HomePage() { 4 | return ( 5 | 6 | 7 | 8 | ); 9 | } 10 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/pages/shopPage/shopPage.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./shopPage.scss"; 3 | import { Route, Switch } from "react-router-dom"; 4 | import CategoryItem from "../../components/category/category.component"; 5 | import ShopItem from "../../components/shop-items/shop-items.component"; 6 | 7 | export default function ShopPage(props) { 8 | return ( 9 |
10 | 11 | {/*
12 | {props.match.isExact ? ( 13 |

Select any category

14 | ) : ( 15 | 16 | )} 17 |
*/} 18 | 19 | {/* */} 20 | 21 | 22 |
23 | ); 24 | } 25 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/pages/shopPage/shopPage.scss: -------------------------------------------------------------------------------- 1 | .shopPage { 2 | height: 100%; 3 | margin: 0 auto; 4 | display: grid; 5 | grid-template-columns: 1fr 4fr; 6 | grid-gap: 1rem; 7 | } 8 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/pages/sign-in-and-sign-up/sign-in-and-sign-up.component.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./sign-in-and-sign-up.styles.scss"; 3 | 4 | import SignIn from "../../components/sign-in/sign-in.component"; 5 | 6 | import SignUp from "../../components/sign-up/sign-up.component"; 7 | 8 | const SignInAndSignUpPage = () => ( 9 |
10 | 11 | 12 |
13 | ); 14 | 15 | export default SignInAndSignUpPage; 16 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/pages/sign-in-and-sign-up/sign-in-and-sign-up.styles.scss: -------------------------------------------------------------------------------- 1 | .sign-in-and-sign-up { 2 | width: 850px; 3 | display: flex; 4 | justify-content: space-between; 5 | margin: 30px auto; 6 | } 7 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/cart/cart.action.js: -------------------------------------------------------------------------------- 1 | import CartActionTypes from "./cart.types"; 2 | 3 | export const toggleCartHidden = () => ({ 4 | type: CartActionTypes.TOGGLE_CART_HIDDEN, 5 | }); 6 | 7 | export const addItem = (item) => ({ 8 | type: CartActionTypes.ADD_ITEM, 9 | payload: item, 10 | }); 11 | 12 | export const clearItemFromCart = (item) => ({ 13 | type: CartActionTypes.CLEAR_ITEM_FROM_CART, 14 | payload: item, 15 | }); 16 | 17 | export const removeItem = (item) => ({ 18 | type: CartActionTypes.REMOVE_ITEM, 19 | payload: item, 20 | }); 21 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/cart/cart.reducer.js: -------------------------------------------------------------------------------- 1 | import CartActionTypes from "./cart.types"; 2 | import { addItemToCart, removeItemToCart } from "./cart.utils"; 3 | const INTIAL_STATE = { 4 | hidden: true, 5 | cartItems: [], 6 | }; 7 | 8 | const CartReducer = (state = INTIAL_STATE, action) => { 9 | switch (action.type) { 10 | case CartActionTypes.TOGGLE_CART_HIDDEN: 11 | return { 12 | ...state, 13 | hidden: !state.hidden, 14 | }; 15 | 16 | case CartActionTypes.ADD_ITEM: 17 | return { 18 | ...state, 19 | cartItems: addItemToCart(state.cartItems, action.payload), 20 | }; 21 | 22 | case CartActionTypes.CLEAR_ITEM_FROM_CART: 23 | return { 24 | ...state, 25 | cartItems: state.cartItems.filter( 26 | (cartItem) => cartItem._id !== action.payload._id 27 | ), 28 | }; 29 | 30 | case CartActionTypes.REMOVE_ITEM: 31 | return { 32 | ...state, 33 | cartItems: removeItemToCart(state.cartItems, action.payload), 34 | }; 35 | 36 | default: 37 | return state; 38 | } 39 | }; 40 | 41 | export default CartReducer; 42 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/cart/cart.selectors.js: -------------------------------------------------------------------------------- 1 | // import { createSelector } from "reselect"; 2 | 3 | // const selectCart = (state) => state.cart; 4 | 5 | // export const selectCartItems = createSelector( 6 | // [selectCart], 7 | // (cart) => cart.cartItems 8 | // ); 9 | 10 | // export const selectCartHidden = createSelector( 11 | // [selectCart], 12 | // (cart) => cart.hidden 13 | // ); 14 | 15 | export const selectCartItemsCount = (cartItems) => 16 | cartItems.reduce( 17 | (accumalatedQuantity, cartItem) => accumalatedQuantity + cartItem.quantity, 18 | 0 19 | ); 20 | 21 | export const selectCartTotal = (cartItems) => 22 | cartItems.reduce( 23 | (accumalatedQuantity, cartItem) => 24 | accumalatedQuantity + cartItem.quantity * cartItem.price, 25 | 0 26 | ); 27 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/cart/cart.types.js: -------------------------------------------------------------------------------- 1 | const CartActionTypes = { 2 | TOGGLE_CART_HIDDEN: 'TOGGLE_CART_HIDDEN', 3 | ADD_ITEM: 'ADD_ITEM', 4 | CLEAR_ITEM_FROM_CART: 'CLEAR_ITEM_FROM_CART', 5 | REMOVE_ITEM: 'REMOVE_ITEM' 6 | 7 | } 8 | 9 | export default CartActionTypes -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/cart/cart.utils.js: -------------------------------------------------------------------------------- 1 | export const addItemToCart = (cartItems, cartItemToAdd) => { 2 | const existingCartItem = cartItems.find( 3 | (cartItem) => cartItem._id === cartItemToAdd._id 4 | ); 5 | 6 | if (existingCartItem) { 7 | return cartItems.map((cartItem) => 8 | cartItem._id === cartItemToAdd._id 9 | ? { ...cartItem, quantity: cartItem.quantity + 1 } 10 | : cartItem 11 | ); 12 | } 13 | 14 | return [...cartItems, { ...cartItemToAdd, quantity: 1 }]; 15 | }; 16 | 17 | export const removeItemToCart = (cartItems, cartItemToRemove) => { 18 | const existingCartItem = cartItems.find( 19 | (cartItem) => cartItem._id === cartItemToRemove._id 20 | ); 21 | 22 | if (existingCartItem.quantity === 1) { 23 | return cartItems.filter( 24 | (cartItem) => cartItem._id !== cartItemToRemove._id 25 | ); 26 | } 27 | 28 | return cartItems.map((cartItem) => 29 | cartItem._id === cartItemToRemove._id 30 | ? { ...cartItem, quantity: cartItem.quantity - 1 } 31 | : cartItem 32 | ); 33 | }; 34 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/producs/products.action.js: -------------------------------------------------------------------------------- 1 | import { productActionTypes } from "./products.actionTypes"; 2 | import axios from "axios"; 3 | export const getProductByCategory = (category) => (dispatch) => { 4 | axios 5 | .get(`/api/v1/product/${category}`) 6 | .then((res) => { 7 | dispatch({ 8 | type: productActionTypes.GET_PRODUCT, 9 | payload: res.data, 10 | }); 11 | }) 12 | .catch((err) => console.log(err)); 13 | }; 14 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/producs/products.actionTypes.js: -------------------------------------------------------------------------------- 1 | export const productActionTypes = { 2 | GET_PRODUCT: "GET_PRODUCT", 3 | }; 4 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/producs/products.reducer.js: -------------------------------------------------------------------------------- 1 | import { productActionTypes } from "./products.actionTypes"; 2 | 3 | const INITAL_STATE = { 4 | product: [], 5 | }; 6 | const productReducer = (state = INITAL_STATE, action) => { 7 | switch (action.type) { 8 | case productActionTypes.GET_PRODUCT: 9 | return { 10 | ...state, 11 | product: action.payload, 12 | }; 13 | 14 | default: 15 | return state; 16 | } 17 | }; 18 | 19 | export default productReducer; 20 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/root-reducer.js: -------------------------------------------------------------------------------- 1 | import { combineReducers } from "redux"; 2 | 3 | import productReducer from "./producs/products.reducer"; 4 | import CartReducer from "./cart/cart.reducer"; 5 | import userReducer from "./user/user.reducer"; 6 | 7 | export default combineReducers({ 8 | products: productReducer, 9 | cart: CartReducer, 10 | user: userReducer, 11 | }); 12 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/store.js: -------------------------------------------------------------------------------- 1 | import { createStore, applyMiddleware, compose } from "redux"; 2 | import thunk from "redux-thunk"; 3 | import logger from "redux-logger"; 4 | 5 | import rootReducer from "./root-reducer"; 6 | 7 | const middleware = [thunk, logger]; 8 | 9 | const store = createStore( 10 | rootReducer, 11 | compose( 12 | applyMiddleware(...middleware), 13 | window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() 14 | ) 15 | ); 16 | 17 | export default store; 18 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/user/user.actions.js: -------------------------------------------------------------------------------- 1 | import { UserActionTypes } from "./user.types"; 2 | 3 | import axios from "axios"; 4 | // import setAuthToken from "../../utils/set-authToken"; 5 | 6 | export const registerUser = (user) => (dispatch) => { 7 | axios 8 | .post("api/v1/user/register", user) 9 | .then((res) => console.log(res)) 10 | .catch((err) => console.log(err)); 11 | }; 12 | 13 | // Login - Get User Token 14 | export const loginUser = (user, history) => (dispatch) => { 15 | axios 16 | .post(`/api/v1/user/login`, user) 17 | .then((res) => { 18 | // save token 19 | const { token, user } = res.data; 20 | 21 | // set token to headers 22 | localStorage.setItem("jwtToken", token); 23 | // set token to headers 24 | // setAuthToken(token); 25 | // const decoded = jwt_decode(token); 26 | // console.log(history); 27 | 28 | // set current user in redux store 29 | dispatch(setCurrentUser(user)); 30 | history.push("/shop"); 31 | }) 32 | .catch((err) => console.log(err)); 33 | }; 34 | 35 | // set looged in user 36 | 37 | export const setCurrentUser = (user) => { 38 | return { 39 | type: UserActionTypes.SET_CURRENT_USER, 40 | payload: user, 41 | }; 42 | }; 43 | 44 | // set logged out user 45 | 46 | export const logoutUser = () => (dispatch) => { 47 | localStorage.removeItem("jwtToken"); 48 | dispatch(setCurrentUser(null)); 49 | }; 50 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/user/user.reducer.js: -------------------------------------------------------------------------------- 1 | import { UserActionTypes } from "./user.types"; 2 | 3 | const INITIAL_STATE = { 4 | currentUser: null, 5 | }; 6 | 7 | const userReducer = (state = INITIAL_STATE, action) => { 8 | switch (action.type) { 9 | case UserActionTypes.SET_CURRENT_USER: 10 | return { 11 | ...state, 12 | currentUser: action.payload, 13 | }; 14 | 15 | default: 16 | return state; 17 | } 18 | }; 19 | export default userReducer; 20 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/user/user.selector.js: -------------------------------------------------------------------------------- 1 | import { createSelector } from 'reselect' 2 | 3 | const selectUser = state => state.user; 4 | 5 | export const selectCurrentUser = createSelector( 6 | [selectUser], 7 | (user) => user.currentUser 8 | ) 9 | -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/redux/user/user.types.js: -------------------------------------------------------------------------------- 1 | export const UserActionTypes = { 2 | SET_CURRENT_USER: 'SET_CURRENT_USER' 3 | } -------------------------------------------------------------------------------- /ecommerce-store/frontend/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /example-express.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3000 4 | 5 | app.get('/', (req, res) => { 6 | res.send('Hello World!') 7 | }) 8 | 9 | app.listen(port, () => { 10 | console.log(`Example app listening at http://localhost:${port}`) 11 | }) 12 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | console.log("Hello, World!"); -------------------------------------------------------------------------------- /fb-static.js: -------------------------------------------------------------------------------- 1 | const puppeteer = require('puppeteer-extra'); 2 | const StealthPlugin = require('puppeteer-extra-plugin-stealth'); 3 | 4 | puppeteer.use(StealthPlugin()); 5 | 6 | const AdblockerPlugin = require('puppeteer-extra-plugin-adblocker'); 7 | puppeteer.use(AdblockerPlugin({ blockTrackers: true })); 8 | 9 | const chromePaths = require('chrome-paths'); 10 | const cheerio = require('cheerio'); 11 | const sleep = ms => new Promise(res => setTimeout(res, ms)); 12 | 13 | (async () => { 14 | const browser = await puppeteer.launch({ 15 | headless: false, 16 | args: [ 17 | "no-sandbox", 18 | "--disable-notifications" 19 | ] 20 | }); 21 | 22 | let allPage = await browser.pages(); 23 | const page = await allPage[0]; 24 | await page.goto('https://www.facebook.com/login/device-based/regular/login/', { 25 | waitUntil: 'networkidle2', 26 | }); 27 | 28 | await page.waitForSelector('#email'); 29 | await page.focus('#email'); 30 | await page.keyboard.type('MASUKAN EMAIL FACEBOOK DISINI'); 31 | 32 | await page.waitForSelector('#pass'); 33 | await page.focus('#pass'); 34 | await page.keyboard.type('MASUKAN PASSWORD FACEBOOK DISINI'); 35 | 36 | const contentHtml = await page.content(); 37 | const $ = cheerio.load(contentHtml); 38 | 39 | const userinfo = $('span.x1lliihq').text(); 40 | const result = $('#loginbutton').attr('id') 41 | console.log("Berhasil Login Dengan username " + userinfo) 42 | 43 | await page.waitForSelector(`#${result}`); 44 | await page.evaluate((result) => document.querySelector(`#${result}`).click(), result); 45 | await sleep(10000); 46 | 47 | if (page.url() == 'https://www.facebook.com/') { 48 | await page.goto('MASUKAN POSTINGAN DISINI', { 49 | waitUntil: 'networkidle2', 50 | }) 51 | console.log("Berhasil Login....") 52 | await sleep(3000,(console.log('Mencoba Comment...\n'))); 53 | const comment = await allPage[0] 54 | 55 | await comment.waitForSelector('div > .x1ed109x > .xh8yej3 > .x78zum5 > .xi81zsa') 56 | await comment.click('div > .x1ed109x > .xh8yej3 > .x78zum5 > .xi81zsa') 57 | await comment.click('form.x1ed109x'); 58 | 59 | await sleep(3000,(console.log("Memasukan Comment...\n"))); 60 | await comment.keyboard.type('Test Auto Comment Bot'); 61 | 62 | 63 | await page.keyboard.press('Enter'); 64 | await sleep(3000,(console.log("Berhasil Comment..."))); 65 | } else { 66 | console.log('gagal load halaman nih...') 67 | } 68 | })(); 69 | -------------------------------------------------------------------------------- /fb-web-automation/README.md: -------------------------------------------------------------------------------- 1 | npm i 2 | atau 3 | npm install puppeteer 4 | npm install puppeteer-extra 5 | npm install puppeteer-extra-plugin-stealth 6 | npm install chrome-paths 7 | npm install cheerio 8 | npm install prompt-sync 9 | npm install fs -------------------------------------------------------------------------------- /fb-web-automation/ascii.txt: -------------------------------------------------------------------------------- 1 | 2 | ___ _ _ 3 | /'___( ) ( )_ 4 | | (__ | |_ ___ _ ___ ___ ___ ___ __ ___ | ,_) 5 | | ,__)| '_`\ /'___)/'_`\/' _ ` _ `/' _ ` _ `\/'__`/' _ `| | 6 | | | | |_) ) ( (___( (_) | ( ) ( ) | ( ) ( ) ( ___| ( ) | |_ 7 | (_) (_,__/' `_____`\___/(_) (_) (_(_) (_) (_`\____(_) (_`\__)_ 8 | ( ) ( )_ ( )_ _ 9 | _ _ _ __ | |_ _ _ _ _| ,_) _ ___ ___ _ _| ,_(_) _ ___ 10 | ( ) ( ) ( )/'__`| '_`\ /'_` ( ) ( | | /'_`\/' _ ` _ `\/'_` | | | |/'_`\/' _ `\ 11 | | \_/ \_/ ( ___| |_) ) ( (_| | (_) | |_( (_) | ( ) ( ) ( (_| | |_| ( (_) | ( ) | 12 | `\___x___/`\____(_,__/' `\__,_`\___/`\__`\___/(_) (_) (_`\__,_`\__(_`\___/(_) (_) 13 | 14 | Author : https://github.com/afdipratama 15 | Project : Web Automation Comment With Node.JS 16 | Platform : Facebook 17 | -------------------------------------------------------------------------------- /fb-web-automation/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scrapping", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "type": "modules", 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "chalk": "^5.1.2", 14 | "cheerio": "^1.0.0-rc.12", 15 | "chrome-paths": "^1.0.1", 16 | "fs": "^0.0.1-security", 17 | "node-fetch": "^2.6.0", 18 | "prompt": "^1.3.0", 19 | "prompt-sync": "^4.2.0", 20 | "pupeteer": "^0.0.1", 21 | "puppeteer": "^19.0.0", 22 | "puppeteer-autoscroll-down": "^1.1.1", 23 | "puppeteer-extra": "^3.3.4", 24 | "puppeteer-extra-plugin-adblocker": "^2.13.5", 25 | "puppeteer-extra-plugin-stealth": "^2.11.1", 26 | "readline": "^1.3.0", 27 | "readline-sync": "^1.4.10" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /firebaseStorage.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const app = express(); 3 | const multer = require("multer"); 4 | const upload = multer(); 5 | 6 | const firebaseStorage = require("./lib/firebase_storage"); 7 | 8 | const uuid = require("uuid"); 9 | 10 | app.post("/upload", upload.single("avatar"), async (req, res, next) => { 11 | const alloweFileType = ["image/png", "image/jpeg"]; 12 | const splitNameFile = req.file.originalname.split("."); 13 | const formatFile = splitNameFile[splitNameFile.length - 1]; 14 | 15 | if (alloweFileType.includes(req.file.mimetype)) { 16 | const image = await firebaseStorage.upload( 17 | req.file.buffer, 18 | `image/${uuid.v4()}.${formatFile}` 19 | ); 20 | 21 | // todo something 22 | return res.status(200).json({ 23 | status: 200, 24 | result: { 25 | image: image.image, 26 | url: image.publicUrl, 27 | }, 28 | }); 29 | } 30 | 31 | res.status(400).json({ 32 | status: 400, 33 | message: "upload file failed", 34 | }); 35 | }); 36 | 37 | app.listen(3000, () => { 38 | console.log("Application running on port 3000"); 39 | }); 40 | -------------------------------------------------------------------------------- /fizzBuzz.js: -------------------------------------------------------------------------------- 1 | export const fizzBuzz = (str) => { 2 | for (var i = 0; i <= 100; i++) { 3 | str = (i % 5 == 0 && i % 3 == 0) ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0) ? "Buzz" : i); 4 | return str 5 | } 6 | } -------------------------------------------------------------------------------- /fuction-reveal: -------------------------------------------------------------------------------- 1 | function reveal() { 2 | document.querySelector('.merrywrap').style.backgroundColor = 'transparent'; 3 | 4 | loop(); 5 | 6 | var w, h; 7 | if (window.innerWidth >= 1000) { 8 | w = 295; 9 | h = 185; 10 | } else { 11 | w = 255; 12 | h = 155; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /function-jam-digital: -------------------------------------------------------------------------------- 1 | ``` 2 | function animation(span) { 3 | span.className = "turn"; 4 | setTimeout(function() { 5 | span.className = ""; 6 | }, 700); 7 | } 8 | 9 | function jam(){ 10 | setInterval(function() { 11 | var waktu = new Date(); 12 | var jam = document.getElementById('jam'); 13 | var hours = waktu.getHours(); 14 | var minutes = waktu.getMinutes(); 15 | var seconds = waktu.getSeconds(); 16 | 17 | if (waktu.getHours() < 10) { 18 | hours = '0' + waktu.getHours(); 19 | } 20 | if (waktu.getMinutes() < 10) { 21 | minutes = '0' + waktu.getMinutes(); 22 | } 23 | if (waktu.getSeconds() < 10) { 24 | seconds = '0' + waktu.getSeconds(); 25 | } 26 | 27 | jam.innerHTML = ''+hours+'' 28 | + ''+minutes+'' 29 | + ''+seconds+''; 30 | 31 | var spans = jam.getElementByTagName('span'); 32 | animation(spans[2]); 33 | if (seconds == 0) animation(spans[1]); 34 | if (minutes == 0 && seconds == 0) animation(spans[0]); 35 | 36 | }, 1000); 37 | } 38 | 39 | jam(); 40 | ``` 41 | -------------------------------------------------------------------------------- /gabriel.js: -------------------------------------------------------------------------------- 1 | const readline = require('readline') 2 | const rl = readline.createInterface({ 3 | input: process.stdin, 4 | output: process.stdout 5 | }) 6 | 7 | function cashbackCounter(cb, price) { 8 | return 'Rp. ' + Number((cb / 100) * price).toLocaleString('id'); 9 | } 10 | 11 | rl.question('Price : ', (price) => { 12 | rl.question('Casback : ', (cashback) => { 13 | const result = cashbackCounter(cashback, price) 14 | console.log('================[ Cashbac Counter ]================'); 15 | console.log('Price : ', 'Rp.', Number(price).toLocaleString('id')); 16 | console.log('Cashback : ', cashback + '%'); 17 | console.log('Result : ', result) 18 | rl.close(); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /genNameIndo.js: -------------------------------------------------------------------------------- 1 | const generateIndoName = () => 2 | new Promise((resolve, reject) => { 3 | axios('http://ninjaname.horseridersupply.com/indonesian_name.php') 4 | .then(({ data }) => { 5 | const $ = cheerio.load(data); 6 | const result = $( 7 | 'body > div > div.page > div.body > div.content > div:nth-child(5)' 8 | ).html(); 9 | resolve(result.split('
')[0].split('\t\n•')[1].trim()); 10 | }) 11 | .catch((err) => { 12 | reject(err); 13 | }); 14 | }); 15 | 16 | module.export = { generateIndoName }; 17 | -------------------------------------------------------------------------------- /genUniqueId.js: -------------------------------------------------------------------------------- 1 | const genUniqueId = (length) => 2 | new Promise((resolve, reject) => { 3 | var text = ''; 4 | var possible = 'abcdefghijklmnopqrstuvwxyz1234567890'; 5 | 6 | for (var i = 0; i < length; i++) 7 | text += possible.charAt(Math.floor(Math.random() * possible.length)); 8 | 9 | resolve(text); 10 | }); 11 | 12 | module.export = { genUniqueId }; 13 | -------------------------------------------------------------------------------- /genre.js: -------------------------------------------------------------------------------- 1 | #routes/genres.js 2 | 3 | var express = require('express'); 4 | var router = express.Router(); 5 | const mongoose = require('mongoose') 6 | const Genre = require('../models/Genre' 7 | -------------------------------------------------------------------------------- /gimenz.js: -------------------------------------------------------------------------------- 1 | const readline = require('readline') 2 | const rl = readline.createInterface({ 3 | input: process.stdin, 4 | output: process.stdout 5 | }) 6 | 7 | function cashbackCounter(cb, price) { 8 | return 'Rp. ' + Number((cb / 100) * price).toLocaleString('id'); 9 | } 10 | 11 | rl.question('Price : ', (price) => { 12 | rl.question('Casback : ', (cashback) => { 13 | const result = cashbackCounter(cashback, price) 14 | console.log('================[ Cashbac Counter ]================'); 15 | console.log('Price : ', 'Rp.', Number(price).toLocaleString('id')); 16 | console.log('Cashback : ', cashback + '%'); 17 | console.log('Result : ', result) 18 | rl.close(); 19 | }); 20 | }); -------------------------------------------------------------------------------- /gitlab/data.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "Juan Daniel", 4 | "email": "email@email.com" 5 | } 6 | ] -------------------------------------------------------------------------------- /gitlab/index.js: -------------------------------------------------------------------------------- 1 | const chalk = require('chalk'); 2 | const fs = require('fs'); 3 | const fetch = require('node-fetch'); 4 | const { URLSearchParams } = require('url'); 5 | 6 | const password = "password" 7 | 8 | const GIT_TOKEN = ''; 9 | const GIT_URL = '' 10 | 11 | const createAccount = async (account) => { 12 | const res = await fetch(GIT_URL, { 13 | method: 'POST', 14 | headers: { 15 | 'Content-Type': 'application/json', 16 | 'PRIVATE-TOKEN': GIT_TOKEN, 17 | }, 18 | body: JSON.stringify({...account}), 19 | }) 20 | return res.json(); 21 | } 22 | 23 | const inviteToGroup = async (account) => { 24 | const res = await fetch(GIT_URL, { 25 | method: 'POST', 26 | headers: { 27 | 'Content-Type': 'application/x-www-form-urlencoded', 28 | 'PRIVATE-TOKEN': GIT_TOKEN, 29 | }, 30 | body: new URLSearchParams({ 31 | 'user_id': account.id, 32 | 'access_level': 50, 33 | }), 34 | }); 35 | 36 | return res.json(); 37 | } 38 | 39 | 40 | (async() => { 41 | const file = fs.readFileSync('data.json', 'utf8'); 42 | const data = JSON.parse(file); 43 | 44 | for (const account of data) { 45 | const account = { 46 | username: account.email.split('@')[0], 47 | name: account.name, 48 | email: account.email, 49 | password, 50 | } 51 | 52 | try { 53 | const response = await createAccount(account); 54 | console.log(chalk.green(`${response.name} berhasil dibuat`)); 55 | const invite = await inviteToGroup(crot); 56 | console.log(chalk.green(`${invite.name} berhasil dimasukin ke group`)); 57 | } catch (err) { 58 | console.log(err); 59 | } 60 | } 61 | })(); -------------------------------------------------------------------------------- /gitlab/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gitaccount", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "chalk": "^4.1.2", 14 | "node-fetch": "^2.6.0" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /guideau.js: -------------------------------------------------------------------------------- 1 | console.log('Hello World, Hell and Heaven'); -------------------------------------------------------------------------------- /halodunia.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3000 4 | 5 | app.get('/', (req, res) => { 6 | res.send('Hello World!') 7 | }) 8 | 9 | app.listen(port, () => { 10 | console.log(`Example app listening at http://localhost:${port}`) 11 | }) 12 | -------------------------------------------------------------------------------- /hasbi-array-to-object.js: -------------------------------------------------------------------------------- 1 | const data = [ 2 | { id: 1, name: "john" }, 3 | { id: 2, name: "doe" }, 4 | ]; 5 | 6 | (() => { 7 | console.log( 8 | data.reduce((obj, item) => { 9 | obj[item.id] = item; 10 | return obj; 11 | }, {}) 12 | ); 13 | })(); 14 | -------------------------------------------------------------------------------- /hello-world.js: -------------------------------------------------------------------------------- 1 | # hello world 2 | console.log("Hello World"); 3 | -------------------------------------------------------------------------------- /httpserver.js: -------------------------------------------------------------------------------- 1 | var http = require("http"); // Ask Node.js to 2 | http.createServer(function(request,response) { 3 |   response.writeHead(200, {"Content-Type": "text/plain"}); 4 |  response.write("Hello World"); 5 | response.end(); 6 | }).listen(8888); 7 | console.log("Server running at http://localhost:8888/") 8 | -------------------------------------------------------------------------------- /janken.js: -------------------------------------------------------------------------------- 1 | function janken(pon){ 2 | return pon[Math.floor(Math.random()*items.length)]; 3 | } 4 | let pon = ["batu","gunting","kertas"]; 5 | console.log(janken(pon)); 6 | -------------------------------------------------------------------------------- /japanese suit.js: -------------------------------------------------------------------------------- 1 | var choices = ["telunjuk", "kelingking", "jempol"]; 2 | var i = Math.floor(Math.random() * 3); 3 | var NPC = choices[i]; 4 | var Point player = 0; 5 | var Point NPC = 0; 6 | function score(){ 7 | var score_div = document.getElementById("score").innerHTML = Point player + " - " + Point NPC; 8 | } 9 | setInterval(score, 50); 10 | function convert(word){ 11 | if(word === "telunjuk") return ''; 12 | if(word === "kelingking") return ''; 13 | return '' 14 | } 15 | function game(UserChoice){ 16 | var box = document.getElementById("challenge"); 17 | box.style.display = "inline-flex"; 18 | var userDiv = document.getElementById("YourObject"); 19 | userDiv.innerHTML = convert(UserChoice); 20 | var comDiv = document.getElementById("ComObject"); 21 | comDiv.innerHTML = convert(NPC); 22 | if(UserChoice === "telunjuk" && NPC === "kelingking" || UserChoice === "kelingking" && NPC === "jempol" || UserChoice === "jempol" && NPC === "telunjuk"){ 23 | win(UserChoice); 24 | } 25 | else if(UserChoice === NPC){ 26 | draw(UserChoice); 27 | } 28 | else{ 29 | lose(UserChoice); 30 | } 31 | function continuGame(){ 32 | i = Math.floor(Math.random() * 3); 33 | NPC = choices[i]; 34 | box.style.display = "none"; 35 | } 36 | setTimeout(continuGame, 1200); 37 | } 38 | function win(bn){ 39 | Point player++; 40 | document.getElementById("who").innerHTML = "kamu menang!"; 41 | var bn = document.getElementById(bn); 42 | bn.classList.remove("bn"); 43 | bn.classList.add("green"); 44 | setTimeout(() => { 45 | bn.classList.add("bn"); 46 | bn.classList.remove("green"); 47 | }, 1200); 48 | } 49 | function draw(bn){ 50 | document.getElementById("who").innerHTML = "Seimbang"; 51 | var bn = document.getElementById(bn); 52 | bn.classList.remove("bn"); 53 | bn.classList.add("gray"); 54 | setTimeout(() => { 55 | bn.classList.add("bn"); 56 | bn.classList.remove("gray"); 57 | }, 1200); 58 | } 59 | function lose(bn){ 60 | Point NPC++; 61 | document.getElementById("who").innerHTML = "Kamu Kalah...."; 62 | var bn = document.getElementById(bn); 63 | bn.classList.remove("bn"); 64 | bn.classList.add("red"); 65 | setTimeout(() => { 66 | bn.classList.add("bn"); 67 | bn.classList.remove("red"); 68 | }, 1200); 69 | } 70 | -------------------------------------------------------------------------------- /jepangsiut.js: -------------------------------------------------------------------------------- 1 | var choices = ["telunjuk", "kelingking", "jempol"]; 2 | var i = Math.floor(Math.random() * 3); 3 | var NPC = choices[i]; 4 | var Point player = 0; 5 | var Point NPC = 0; 6 | function score(){ 7 | var score_div = document.getElementById("score").innerHTML = Point player + " - " + Point NPC; 8 | } 9 | setInterval(score, 50); 10 | function convert(word){ 11 | if(word === "telunjuk") return ''; 12 | if(word === "kelingking") return ''; 13 | return '' 14 | } 15 | function game(UserChoice){ 16 | var box = document.getElementById("challenge"); 17 | box.style.display = "inline-flex"; 18 | var userDiv = document.getElementById("YourObject"); 19 | userDiv.innerHTML = convert(UserChoice); 20 | var comDiv = document.getElementById("ComObject"); 21 | comDiv.innerHTML = convert(NPC); 22 | if(UserChoice === "telunjuk" && NPC === "kelingking" || UserChoice === "kelingking" && NPC === "jempol" || UserChoice === "jempol" && NPC === "telunjuk"){ 23 | win(UserChoice); 24 | } 25 | else if(UserChoice === NPC){ 26 | draw(UserChoice); 27 | } 28 | else{ 29 | lose(UserChoice); 30 | } 31 | function continuGame(){ 32 | i = Math.floor(Math.random() * 3); 33 | NPC = choices[i]; 34 | box.style.display = "none"; 35 | } 36 | setTimeout(continuGame, 1200); 37 | } 38 | function win(bn){ 39 | Point player++; 40 | document.getElementById("who").innerHTML = "kamu menang!"; 41 | var bn = document.getElementById(bn); 42 | bn.classList.remove("bn"); 43 | bn.classList.add("green"); 44 | setTimeout(() => { 45 | bn.classList.add("bn"); 46 | bn.classList.remove("green"); 47 | }, 1200); 48 | } 49 | function draw(bn){ 50 | document.getElementById("who").innerHTML = "Seimbang"; 51 | var bn = document.getElementById(bn); 52 | bn.classList.remove("bn"); 53 | bn.classList.add("gray"); 54 | setTimeout(() => { 55 | bn.classList.add("bn"); 56 | bn.classList.remove("gray"); 57 | }, 1200); 58 | } 59 | function lose(bn){ 60 | Point NPC++; 61 | document.getElementById("who").innerHTML = "Kamu Kalah...."; 62 | var bn = document.getElementById(bn); 63 | bn.classList.remove("bn"); 64 | bn.classList.add("red"); 65 | setTimeout(() => { 66 | bn.classList.add("bn"); 67 | bn.classList.remove("red"); 68 | }, 1200); 69 | } 70 | -------------------------------------------------------------------------------- /json-to-file.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | const JSONToFile = (obj, filename) => 4 | fs.writeFileSync(`${filename}.json`, JSON.stringify(obj, null, 2)); 5 | -------------------------------------------------------------------------------- /kafkatest/.gitignore: -------------------------------------------------------------------------------- 1 | ./node_modules/ -------------------------------------------------------------------------------- /kafkatest/consumer-cli.sh: -------------------------------------------------------------------------------- 1 | docker run -it --rm --network app-tier -e KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper-server:2181 bitnami/kafka:latest kafka-console-consumer.sh --bootstrap-server 172.18.0.3:9092 --topic berita --group reader 2 | -------------------------------------------------------------------------------- /kafkatest/consumer.js: -------------------------------------------------------------------------------- 1 | const { Kafka, logLevel } = require('kafkajs'); 2 | 3 | const host = '127.0.0.1'; 4 | 5 | const kafka = new Kafka({ 6 | logLevel: logLevel.INFO, 7 | brokers: [`${host}:9092`], 8 | clientId: 'example-consumer', 9 | }); 10 | 11 | const topic = 'com.examplemessage.events.incident.status.changed'; 12 | const consumer = kafka.consumer({ groupId: 'test-group' }); 13 | 14 | const run = async () => { 15 | await consumer.connect(); 16 | await consumer.subscribe({ topic, fromBeginning: true }); 17 | 18 | await consumer.run({ 19 | eachMessage: async ({ topic, partition, message }) => { 20 | // const prefix = `${topic}[${partition} | ${message.offset}] / ${message.timestamp}` 21 | // console.log(`- ${prefix} ${message.key}#${message.value}`) 22 | 23 | console.log(message.value.toString('utf-8')); 24 | 25 | console.log('----------------------------'); 26 | 27 | }, 28 | }); 29 | } 30 | 31 | run().catch(e => console.error(`[example/consumer] ${e.message}`, e)); 32 | -------------------------------------------------------------------------------- /kafkatest/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | zookeeper: 4 | image: wurstmeister/zookeeper:latest 5 | ports: 6 | - "2181:2181" 7 | kafka: 8 | image: wurstmeister/kafka:2.11-1.1.1 9 | ports: 10 | - "9092:9092" 11 | links: 12 | - zookeeper 13 | environment: 14 | KAFKA_ADVERTISED_HOST_NAME: "127.0.0.1" 15 | KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 16 | KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'true' 17 | KAFKA_DELETE_TOPIC_ENABLE: 'true' 18 | KAFKA_CREATE_TOPICS: "topic-test:1:1" 19 | volumes: 20 | - /var/run/docker.sock:/var/run/docker.sock 21 | -------------------------------------------------------------------------------- /kafkatest/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kafkatest", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "kafkajs": "^1.16.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /kafkatest/producer-cli.sh: -------------------------------------------------------------------------------- 1 | docker run -it --rm --network app-tier -e KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper-server:2181 bitnami/kafka:latest kafka-console-producer.sh --bootstrap-server 172.18.0.3:9092 --topic berita 2 | -------------------------------------------------------------------------------- /kafkatest/producer.js: -------------------------------------------------------------------------------- 1 | const { Kafka, logLevel } = require('kafkajs') 2 | 3 | const host = '127.0.0.1' 4 | 5 | const kafka = new Kafka({ 6 | logLevel: logLevel.DEBUG, 7 | brokers: [`${host}:9092`], 8 | clientId: 'example-producer', 9 | }) 10 | 11 | const topic = 'com.examplemessage.events.incident.status.changed'; 12 | const producer = kafka.producer(); 13 | 14 | const sendMessage = () => { 15 | let message = [ 16 | { 17 | key: `KFA0001`, 18 | value: `Kafka message broker at number: ${Math.random()}`, 19 | } 20 | ]; 21 | 22 | return producer 23 | .send({ 24 | topic, 25 | messages: message, 26 | }) 27 | .then(console.log) 28 | .catch(e => console.error(`[example/producer] ${e.message}`, e)); 29 | } 30 | 31 | const run = async () => { 32 | await producer.connect() 33 | setInterval(sendMessage, 3000) 34 | } 35 | 36 | run().catch(e => console.error(`[example/producer] ${e.message}`, e)); 37 | -------------------------------------------------------------------------------- /kantobey.js: -------------------------------------------------------------------------------- 1 | var http = require('http'); 2 | 3 | const createServer = async () => { 4 | await http 5 | .createServer(function (request, response) { 6 | response.writeHead(200, { 'Content-Type': 'text/plain' }); 7 | response.end('Hello my server'); 8 | }) 9 | .listen(3000); 10 | console.log('Server running at port 3000'); 11 | }; 12 | 13 | module.exports = { createServer }; 14 | -------------------------------------------------------------------------------- /kiwiredist.js: -------------------------------------------------------------------------------- 1 | const puppeteer = require('puppeteer'); 2 | const readLineSync = require('readLine-sync'); 3 | const delay = require('delay'); 4 | 5 | (async () => { 6 | 7 | var nomer = readLineSync.question('INPUT RESI : ') 8 | const options = { waituntill: 'networkidle2' } 9 | const browser = await puppeteer.launch({ 10 | headless: false, 11 | }); 12 | const pages = await browser.pages(); 13 | const page = pages[0]; 14 | await page.goto('https://resi.id/lacak-resi-jnt', options); 15 | const res1 = await page.$('#input-single') 16 | await res1.type(nomer) 17 | await delay(1000) 18 | const selector = '#input-single-btn' 19 | await page.evaluate((selector) => document.querySelector(selector).click(), selector); 20 | await delay(3000) 21 | console.log('gud') 22 | if (page.url() == 'https://resi.id/lacak-resi-jnt' ){ 23 | console.log('manteb') 24 | }else{ 25 | console.log('gagal') 26 | }; 27 | console.log('selesai') 28 | await browser.close() 29 | })(); 30 | -------------------------------------------------------------------------------- /leksyking.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const bodyParser = require('body-parser'); 3 | const https = require('https'); 4 | 5 | const app = express(); 6 | 7 | app.set('view engine', 'ejs'); 8 | 9 | app.use(bodyParser.urlencoded({extended: true})); 10 | 11 | app.get("/", (req, res) => { 12 | let today = new Date(); 13 | let options = { 14 | weekday: 'long', 15 | day: 'numeric', 16 | month: 'long', 17 | year: 'numeric' 18 | }; 19 | let day = today.toLocaleDateString('en-US', options); 20 | res.render("weather", { 21 | Today: day, 22 | }); 23 | }); 24 | 25 | app.post("/", (req, res) => { 26 | const city = req.body.place; 27 | const appid = "d8c5d3243355ad76a180185dc2e4935e"; 28 | const unit = "metric"; 29 | const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${appid}&units=${unit}`; 30 | 31 | https.get(url, (response) => { 32 | console.log(response.statusCode); 33 | response.on("data", (data) => { 34 | const WeatherData = JSON.parse(data); 35 | const temp = WeatherData.main.temp; 36 | const description = WeatherData.weather[0].description; 37 | const icon = WeatherData.weather[0].icon; 38 | const imageURL = `http://openweathermap.org/img/wn/${icon}@2x.png` 39 | 40 | res.write(`

The weather is currently ${description}.

`) 41 | res.write(`

The temperature in ${city} is ${temp} degrees celcius.

`); 42 | res.write(``) 43 | res.send(); 44 | }); 45 | }); 46 | }); 47 | 48 | app.listen(3000, () => console.log('Starting the Weather App')); 49 | 50 | -------------------------------------------------------------------------------- /location_api_By_Yasas.js: -------------------------------------------------------------------------------- 1 | const API_KEY = "YOUR_GOOGLE_API_KEY"; 2 | const axios = require("axios"); 3 | 4 | async function getCoordsForAddress(address) { 5 | const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent( 6 | address 7 | )}&key=${API_KEY} 8 | `; 9 | 10 | const response = await axios.get(url); 11 | const data = response.data; 12 | 13 | if (!data || data.status === "ZERO_RESULTS") { 14 | const error = new HttpError("Could not find the location", 422); 15 | throw error; 16 | } 17 | if (data.status === "REQUEST_DENIED") { 18 | const error = new HttpError("REQUEST_DENIED" + data.error_message, 422); 19 | throw error; 20 | } 21 | 22 | const coordinates = data.results[0].geometry.location; 23 | return coordinates; 24 | } 25 | 26 | // Custom Error Handler 27 | class HttpError extends Error { 28 | constructor(message, errorCode) { 29 | super(message); //Add a 'message' property super class-Error 30 | this.code = errorCode; //Adds a "code" property 31 | } 32 | } 33 | 34 | // module.exports = getCoordsForAddress; 35 | // module.exports = HttpError; 36 | 37 | // Contributed by - Yasas Sandeepa 38 | // Undergraduate- University of Moratuwa 39 | // Sri Lanka -------------------------------------------------------------------------------- /lunaditu_pyramid.js: -------------------------------------------------------------------------------- 1 | /* 2 | MODULE DONE BY https://github.com/Lunaditu 3 | 4 | This module checks if the given array has a pyramid pattern and returns true if so. 5 | */ 6 | 7 | /** 8 | * @param {Array} array 9 | * @param {String} seperator (default is space (' ')) 10 | * @returns Boolean -> isPyramid 11 | */ 12 | function Streak (array, seperator=' ') { 13 | if (array.length%2 == 0) return; 14 | let first = array[0]; 15 | let mid = (array.length+1)/2; 16 | let cont = true; 17 | array.forEach((item, index) => { 18 | if (cont) { 19 | if (item.split(seperator).every((val, i, arr) => val == first)) { cont=true; } 20 | else { cont = false; } 21 | }}); 22 | return cont; 23 | } 24 | 25 | module.exports = {Streak} 26 | 27 | 28 | /* TESTS */ 29 | 30 | let arr1 = [ 31 | 'KEKW', 32 | 'KEKW KEKW', 33 | 'KEKW KEKW KEKW', 34 | 'KEKW KEKW', 35 | 'KEKW' 36 | ]; 37 | 38 | let arr2 = [ 39 | 'KEKW', 40 | 'KEKW KEKW', 41 | 'KEKW KEKW KEKW', 42 | 'KEKW KEKWW', 43 | 'KEKW' 44 | ]; 45 | 46 | console.log(Streak(arr1)); 47 | console.log(Streak(arr2)); -------------------------------------------------------------------------------- /mergeSorty.js: -------------------------------------------------------------------------------- 1 | // merge sort in js 2 | function merge_sort(left_part,right_part) 3 | { 4 | var i = 0; 5 | var j = 0; 6 | var results = []; 7 | 8 | while (i < left_part.length || j < right_part.length) { 9 | if (i === left_part.length) { 10 | // j is the only index left_part 11 | results.push(right_part[j]); 12 | j++; 13 | } 14 | else if (j === right_part.length || left_part[i] <= right_part[j]) { 15 | results.push(left_part[i]); 16 | i++; 17 | } else { 18 | results.push(right_part[j]); 19 | j++; 20 | } 21 | } 22 | return results; 23 | } 24 | 25 | console.log(merge_sort([1,3,4], [3,7,9])); 26 | -------------------------------------------------------------------------------- /minPower.js: -------------------------------------------------------------------------------- 1 | const minimal = (a,b) => { 2 | if (a > b) { 3 | return b; 4 | } else if (a < b) { 5 | return a; 6 | } else { 7 | return a; 8 | } 9 | } 10 | 11 | const power = (a,b) => { 12 | return a**b; 13 | } 14 | 15 | // Example Minimal 16 | console.log(minimal(1, 4)) 17 | console.log(minimal(3, 3)) 18 | 19 | // Example Power 20 | console.log(power(3, 3) ) 21 | console.log(power(4, 0.5)) -------------------------------------------------------------------------------- /models-index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const Sequelize = require('sequelize'); 6 | const basename = path.basename(__filename); 7 | const env = process.env.NODE_ENV || 'development'; 8 | const config = require(__dirname + '/../config/config.json')[env]; 9 | const db = {}; 10 | 11 | let sequelize; 12 | if (config.use_env_variable) { 13 | sequelize = new Sequelize(process.env[config.use_env_variable], config); 14 | } else { 15 | sequelize = new Sequelize(config.database, config.username, config.password, config); 16 | } 17 | 18 | fs 19 | .readdirSync(__dirname) 20 | .filter(file => { 21 | return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); 22 | }) 23 | .forEach(file => { 24 | const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes); 25 | db[model.name] = model; 26 | }); 27 | 28 | Object.keys(db).forEach(modelName => { 29 | if (db[modelName].associate) { 30 | db[modelName].associate(db); 31 | } 32 | }); 33 | 34 | db.sequelize = sequelize; 35 | db.Sequelize = Sequelize; 36 | #Hacktoberfest2022 37 | module.exports = db; 38 | -------------------------------------------------------------------------------- /mongoSetup.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | const db = 'mongoURI'; //Replace the mongoURI with MongoDB URI of your database 3 | 4 | const connectDB = async () => { 5 | try { 6 | await mongoose.connect(db, { 7 | useNewUrlParser: true, 8 | useCreateIndex: true, 9 | useFindAndModify: false, 10 | useUnifiedTopology: true, 11 | }); 12 | console.log('MongoDB Connected'); 13 | } catch (err) { 14 | console.error(err.message); 15 | process.exit(1); 16 | } 17 | }; 18 | 19 | module.exports = connectDB; 20 | -------------------------------------------------------------------------------- /multiply.js: -------------------------------------------------------------------------------- 1 | export const multiplyTwo = (a,b) => a * b -------------------------------------------------------------------------------- /myFirst.js: -------------------------------------------------------------------------------- 1 | var http = require('http'); 2 | 3 | http.createServer(function (req, res) { 4 | res.writeHead(200, {'Content-Type': 'text/html'}); 5 | res.end('Hello World!'); 6 | }).listen(8080); -------------------------------------------------------------------------------- /my_small_node.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | 3 | const app = express(); 4 | 5 | // HTML response 6 | app.get('/', (req, res) => { 7 | return res.send('

Hello World!

'); 8 | }) 9 | 10 | // API response 11 | app.get('/api', (req,res) => { 12 | return res.status(200).json({ 13 | message: "Hello World!" 14 | }) 15 | }) 16 | 17 | 18 | app.listen(2222, ()=> { 19 | console.log(`App running on port ${2222}`); 20 | }) -------------------------------------------------------------------------------- /nodejs-sendmailer/main.js: -------------------------------------------------------------------------------- 1 | const nodemailer = require('nodemailer'); 2 | const fs = require('fs'); 3 | 4 | const main = async () => { 5 | 6 | let transporter = nodemailer.createTransport({ 7 | service: 'gmail', 8 | auth: { 9 | user: 'youraccount@gmail.com', 10 | pass: 'yourpassword' 11 | } 12 | }); 13 | 14 | let sendMessage = await transporter.sendMail({ 15 | from: "Test from my account", 16 | to: "yourfriend@email.com", 17 | subject: "Testing Send Emailer with Nodemailer Package", 18 | html: "

Hello World!

", 19 | attachments: { 20 | filename: 'my-attachment.jpg', 21 | content: fs.createReadStream('./my-picture.jpeg') 22 | } 23 | }); 24 | 25 | console.log('-----------'); 26 | console.log(`Message sent: ${sendMessage.messageId}`); 27 | console.log('-----------'); 28 | } 29 | 30 | main().catch(err => { 31 | console.log(err); 32 | }) -------------------------------------------------------------------------------- /nodejs-sendmailer/my-picture.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kokonior/NodeJS-Projects/94383782aa273c162d2aa7d315ba22e1dcf2ec48/nodejs-sendmailer/my-picture.jpeg -------------------------------------------------------------------------------- /nodejs-sendmailer/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sendmailer", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "send": "node main.js" 9 | }, 10 | "keywords": [], 11 | "author": "", 12 | "license": "ISC", 13 | "dependencies": { 14 | "nodemailer": "^6.6.3" 15 | } 16 | } -------------------------------------------------------------------------------- /passwordGenerator.js: -------------------------------------------------------------------------------- 1 | const passwordGenerator = () => { 2 | const char = 'abcdefghijklmnopqrstuvwxyz'; 3 | const num = '1234567890'; 4 | const symbol = '!@#$%^&*()_+'; 5 | let result = ''; 6 | for (let i = 0; i < 4; i++) { 7 | result += char.charAt(Math.floor(Math.random() * char.length)); 8 | result += num.charAt(Math.floor(Math.random() * num.length)); 9 | result += symbol.charAt(Math.floor(Math.random() * symbol.length)); 10 | } 11 | return result; 12 | } 13 | 14 | console.log(passwordGenerator()); -------------------------------------------------------------------------------- /polaSegitigaSikuSiku.js: -------------------------------------------------------------------------------- 1 | function trianglePattern(height) { 2 | let result = ''; 3 | for (let i = 0; i < height; i++) { 4 | for (let j = 0; j <= i; j++) { 5 | result += "* "; 6 | } 7 | result += "\n"; 8 | } 9 | return result; 10 | } 11 | 12 | console.log(trianglePattern(5)); 13 | -------------------------------------------------------------------------------- /proxyscraper.js: -------------------------------------------------------------------------------- 1 | /* us-proxy.org scraper */ 2 | 3 | const fs = require('fs') 4 | const axios = require('axios') 5 | const cheerio = require('cheerio') 6 | 7 | const UsProxy = ({ saveTo = `us-proxy-${new Date().getTime()}.txt`} = {}) => { 8 | return new Promise(async(resolve, reject) => { 9 | const options = { 10 | headers: { 11 | 'User-Agent': 'googlebot' 12 | } 13 | } 14 | var url = 'https://us-proxy.org/' 15 | try { 16 | var { data: html } = await axios(url) 17 | $ = cheerio.load(html) 18 | var proxy = $('textarea.form-control').text() 19 | proxy = proxy.split('\n').splice(3).join('\n') 20 | if (saveTo) { 21 | fs.writeFileSync(saveTo, proxy) 22 | resolve({ 23 | success: true, 24 | saveTo 25 | }) 26 | } 27 | } catch ({ status }) { 28 | reject({ 29 | message: `Error with status code ${status}` 30 | }) 31 | } 32 | }) 33 | } 34 | 35 | // For testing 36 | UsProxy().then(data => console.log(data)).catch(e => console.log(e)) 37 | 38 | module.exports = UsProxy 39 | -------------------------------------------------------------------------------- /proxytrick.js: -------------------------------------------------------------------------------- 1 | Object.setPrototypeOf( 2 | Number.prototype, 3 | new Proxy(Number.prototype, { 4 | get(_, _end, start) { 5 | // where (start)[_end] 6 | let end = parseInt(_end) 7 | if (isNaN(end)) { 8 | // warning or error 9 | // eventually, fallback 10 | return start 11 | } 12 | 13 | // sort behaviour - default ASC 14 | let s = +1 15 | 16 | if (start > end) { 17 | // swap 18 | let tmp = start 19 | start = end 20 | end = tmp 21 | // sort behaviour - DESC 22 | s = -1 23 | } 24 | 25 | // generate range 26 | return Array(end - start + 1) 27 | .fill() 28 | .map((_, i) => start + i) 29 | .sort(() => s) 30 | }, 31 | }) 32 | ) 33 | 34 | let contoh1 = (1)[10] 35 | console.log(contoh1) // print 1-10 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 36 | 37 | let contoh2 = (10)[1] 38 | console.log(contoh2) // print 10-1 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 39 | -------------------------------------------------------------------------------- /quotes-scraper.js: -------------------------------------------------------------------------------- 1 | const requestPromise = require('request-promise'); 2 | const cheerio = require('cheerio'); 3 | const request = require('request'); 4 | 5 | const baseUrl = 'http://quotes.toscrape.com/'; 6 | const loginUrl = 'login'; 7 | 8 | (async () => { 9 | let html = await requestPromise({ 10 | url: baseUrl + loginUrl, 11 | method: 'GET', 12 | gzip: true, 13 | resolveWithFullResponse: true, 14 | }); 15 | 16 | let cookie = html.headers['set-cookie'].map(value => value.split(';')[0]).join(' '); 17 | 18 | console.log('cookie', cookie); 19 | 20 | let $ = cheerio.load(html.body); 21 | 22 | let csrfToken = $('input[name="csrf_token"]').val(); 23 | 24 | try { 25 | let loginRequest = await requestPromise({ 26 | url: baseUrl + loginUrl, 27 | method: 'POST', 28 | gzip: true, 29 | headers: { 30 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 31 | 'Accept-Encoding': 'gzip, deflate', 32 | 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8', 33 | 'Cache-Control': 'max-age=0', 34 | 'Connection': 'keep-alive', 35 | 'Content-Type': 'application/x-www-form-urlencoded', 36 | 'Host': 'quotes.toscrape.com', 37 | 'Origin': 'http://quotes.toscrape.com', 38 | 'Referer': 'http://quotes.toscrape.com/login', 39 | 'Upgrade-Insecure-Requests': '1', 40 | 'Cookie': cookie, 41 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36' 42 | }, 43 | form: { 44 | 'csrf_token': csrfToken, 45 | 'username': 'admin', 46 | 'password': 'admin', 47 | }, 48 | resolveWithFullResponse: true, 49 | }); 50 | 51 | } catch (err) { 52 | cookie = err.response.headers['set-cookie'].map(value => value.split(';')[0]).join(' '); 53 | } 54 | })(); -------------------------------------------------------------------------------- /rand_x_num.js: -------------------------------------------------------------------------------- 1 | if(!process.argv[2] || isNaN(parseInt(process.argv[2]))){ 2 | throw new Error('Invalid Argument'); 3 | } else { 4 | console.log(Math.floor(Math.random() * Math.pow(process.argv[2], parseInt(1)))); 5 | } 6 | -------------------------------------------------------------------------------- /rand_x_number.js: -------------------------------------------------------------------------------- 1 | if(!process.argv[2] || isNaN(parseInt(process.argv[2]))){ 2 | throw new Error('Invalid Argument'); 3 | } else { 4 | console.log(Math.floor(Math.random() * Math.pow(10, parseInt(process.argv[2])))); 5 | } -------------------------------------------------------------------------------- /random_number.js: -------------------------------------------------------------------------------- 1 | if(!process.argv[2] || isNaN(parseInt(process.argv[2]))){ 2 | throw new Error('Invalid Argument'); 3 | } else { 4 | console.log(Math.floor(Math.random() * Math.pow(10, parseInt(process.argv[2])))); 5 | } 6 | -------------------------------------------------------------------------------- /random_string.js: -------------------------------------------------------------------------------- 1 | const randstr = length => { 2 | var text = ""; 3 | var possible = 4 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890"; 5 | 6 | for (var i = 0; i < length; i++) 7 | text += possible.charAt(Math.floor(Math.random() * possible.length)); 8 | 9 | return text; 10 | }; 11 | 12 | 13 | console.log(randstr()); 14 | -------------------------------------------------------------------------------- /ronin_server.js: -------------------------------------------------------------------------------- 1 | const ronin = require('ronin-server') 2 | const mocks = require('ronin-mocks') 3 | const database = require("ronin-database") 4 | const server = ronin.server() 5 | 6 | database.connect( process.env.CONNECTIONSTRING ) 7 | server.use('/', mocks.server(server.Router(), false, true)) 8 | server.use('/foo', (req, res) => { 9 | return res.json({"foo": "bar"}) 10 | }) 11 | 12 | server.start() -------------------------------------------------------------------------------- /salam.js: -------------------------------------------------------------------------------- 1 | function checkTime(i) { 2 | if (i < 10) { 3 | i = `0` + i; 4 | } 5 | return i; 6 | } 7 | 8 | function salam(nama) { 9 | var ucapanSalam; 10 | var jsDate = new Date(); 11 | var jam = jsDate.getHours(); 12 | var menit = jsDate.getMinutes(); 13 | var detik = jsDate.getSeconds(); 14 | menit = checkTime(menit); 15 | detik = checkTime(detik); 16 | if (jam < 4) { 17 | ucapanSalam = `Selamat Malam ${nama}` 18 | } else if (jam < 11) { 19 | ucapanSalam = `Selamat Pagi ${nama}` 20 | } else if (jam < 15) { 21 | ucapanSalam = `Selamat Siang ${nama}` 22 | } else if (jam < 19) { 23 | ucapanSalam = `Selamat Sore ${nama}` 24 | } else { 25 | ucapanSalam = `Selamat Malam ${nama}` 26 | } 27 | 28 | return ucapanSalam 29 | } 30 | 31 | console.log(salam('melan')); -------------------------------------------------------------------------------- /scisorsgame.js: -------------------------------------------------------------------------------- 1 | var choices = ["paper", "rock", "scissors"]; 2 | var i = Math.floor(Math.random() * 3); 3 | var ComChoice = choices[i]; 4 | var UserPoints = 0; 5 | var ComPoints = 0; 6 | function score(){ 7 | var score_div = document.getElementById("score").innerHTML = UserPoints + " - " + ComPoints; 8 | } 9 | setInterval(score, 50); 10 | function convert(word){ 11 | if(word === "paper") return ''; 12 | if(word === "rock") return ''; 13 | return '' 14 | } 15 | function game(UserChoice){ 16 | var box = document.getElementById("challenge"); 17 | box.style.display = "inline-flex"; 18 | var userDiv = document.getElementById("YourObject"); 19 | userDiv.innerHTML = convert(UserChoice); 20 | var comDiv = document.getElementById("ComObject"); 21 | comDiv.innerHTML = convert(ComChoice); 22 | if(UserChoice === "paper" && ComChoice === "rock" || UserChoice === "rock" && ComChoice === "scissors" || UserChoice === "scissors" && ComChoice === "paper"){ 23 | win(UserChoice); 24 | } 25 | else if(UserChoice === ComChoice){ 26 | draw(UserChoice); 27 | } 28 | else{ 29 | lose(UserChoice); 30 | } 31 | function continuGame(){ 32 | i = Math.floor(Math.random() * 3); 33 | ComChoice = choices[i]; 34 | box.style.display = "none"; 35 | } 36 | setTimeout(continuGame, 1200); 37 | } 38 | function win(bn){ 39 | UserPoints++; 40 | document.getElementById("who").innerHTML = "You win!"; 41 | var bn = document.getElementById(bn); 42 | bn.classList.remove("bn"); 43 | bn.classList.add("green"); 44 | setTimeout(() => { 45 | bn.classList.add("bn"); 46 | bn.classList.remove("green"); 47 | }, 1200); 48 | } 49 | function draw(bn){ 50 | document.getElementById("who").innerHTML = "It's a Draw."; 51 | var bn = document.getElementById(bn); 52 | bn.classList.remove("bn"); 53 | bn.classList.add("gray"); 54 | setTimeout(() => { 55 | bn.classList.add("bn"); 56 | bn.classList.remove("gray"); 57 | }, 1200); 58 | } 59 | function lose(bn){ 60 | ComPoints++; 61 | document.getElementById("who").innerHTML = "You lose..."; 62 | var bn = document.getElementById(bn); 63 | bn.classList.remove("bn"); 64 | bn.classList.add("red"); 65 | setTimeout(() => { 66 | bn.classList.add("bn"); 67 | bn.classList.remove("red"); 68 | }, 1200); 69 | } -------------------------------------------------------------------------------- /scrape-wallpaper.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | const cheerio = require('cheerio') 3 | 4 | function wallpaper(title, page = '1') { 5 | return new Promise((resolve, reject) => { 6 | axios.get(`https://www.besthdwallpaper.com/search?CurrentPage=${page}&q=${title}`) 7 | .then(({ data }) => { 8 | let $ = cheerio.load(data) 9 | let hasil = [] 10 | $('div.grid-item').each(function (a, b) { 11 | hasil.push({ 12 | title: $(b).find('div.info > a > h3').text(), 13 | type: $(b).find('div.info > a:nth-child(2)').text(), 14 | source: 'https://www.besthdwallpaper.com/'+$(b).find('div > a:nth-child(3)').attr('href'), 15 | image: [$(b).find('picture > img').attr('data-src') || $(b).find('picture > img').attr('src'), $(b).find('picture > source:nth-child(1)').attr('srcset'), $(b).find('picture > source:nth-child(2)').attr('srcset')] 16 | }) 17 | }) 18 | // Result Array 19 | resolve(hasil) 20 | }) 21 | }) 22 | } 23 | -------------------------------------------------------------------------------- /select-emulator/example.txt: -------------------------------------------------------------------------------- 1 | List of devices attached 2 | emulator-5554 device 3 | emulator-5554 device 4 | emulator-5554 device 5 | emulator-5554 device 6 | emulator-5554 device 7 | emulator-5554 device 8 | emulator-5554 device 9 | emulator-5554 device 10 | emulator-5554 device 11 | emulator-5554 device 12 | emulator-5554 device 13 | 14 | -------------------------------------------------------------------------------- /select-emulator/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejscli", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC" 11 | } 12 | -------------------------------------------------------------------------------- /select-emulator/selectEmulator.js: -------------------------------------------------------------------------------- 1 | const { spawn,exec } = require('node:child_process'); 2 | const readline = require('readline'); 3 | const rl = readline.createInterface({ 4 | input: process.stdin, 5 | output: process.stdout 6 | }); 7 | const ls = spawn('cat', ['example.txt']); 8 | 9 | ls.stdout.on('data', (data) => { 10 | var d = data.toString().replace("List of devices attached", "") 11 | var remove = d.toString().split(" ") 12 | 13 | const map = remove.map((i, index) => { 14 | var data = i.replace(/(\r\n|\n|\r)/gm, " ") 15 | var dataReplaced = data.replace("device", "") 16 | return dataReplaced.split(' ').join("") 17 | }).slice(0, -1) 18 | 19 | console.log("List emulator yang tersedia") 20 | console.table(map.map((item, index)=> { 21 | return `${item}` 22 | })) 23 | 24 | 25 | rl.question(`Mau ngerun yang mana, pilih by index : `, item => { 26 | exec(`emulator -avd ${map[item]}`, function(err, stdout, stderr) { 27 | // handle err, stdout, stderr 28 | if(err){ 29 | console.log("Emulator tidak tersedia") 30 | } 31 | }); 32 | rl.close() 33 | }) 34 | }); 35 | -------------------------------------------------------------------------------- /sendMail.js: -------------------------------------------------------------------------------- 1 | 2 | const SendMail = (toUser, otp) => { 3 | console.log("send mail running") 4 | const nodemailer = require('nodemailer'); 5 | 6 | let transporter = nodemailer.createTransport({ 7 | host: "smtp.mailtrap.io", 8 | port: 2525, 9 | auth: { 10 | user: "d4b59f0c323fe1", 11 | pass: "749b8c78df003e" 12 | } 13 | }) 14 | 15 | message = { 16 | from: "YOUR_EMAIL", 17 | to: toUser, 18 | subject: "Account Verification", 19 | text: `your registration OTP is ${otp} ` 20 | } 21 | 22 | transporter.sendMail(message, function (err, info) { 23 | if (err) { 24 | console.log("error transporter", err) 25 | } else { 26 | console.log('transporter info', info); 27 | } 28 | }) 29 | } 30 | 31 | module.exports = SendMail 32 | -------------------------------------------------------------------------------- /serverHTTP: -------------------------------------------------------------------------------- 1 | var http = require('http'); 2 | 3 | http.createServer(function ( req, res ) { 4 | 5 | res.writeHead( 200, { 'Content-Type': 'text/plain' } ); 6 | res.end( 'Hello World\n' ); 7 | }).listen( 8080 ); 8 | 9 | console.log( 'Servidor rodando na porta 8080' ); 10 | -------------------------------------------------------------------------------- /simple-server.js: -------------------------------------------------------------------------------- 1 | //load http module 2 | var http = require("http"); 3 | http 4 | .createServer(function (request, response) { 5 | //http header 6 | //tell the browser everything is okey with status code 200 and data text 7 | response.writeHead(200, { "Content-Type": "text/plain" }); 8 | // write the text to your body page 9 | // send the body and header to the server 10 | response.end("Hello my server"); 11 | //tell the server which port you are running 12 | }) 13 | .listen(3000); 14 | //print the message on console 15 | console.log("Server running at port 3000"); 16 | -------------------------------------------------------------------------------- /simpleEncryptor.js: -------------------------------------------------------------------------------- 1 | const key = 'yourkeyhereplease'; 2 | const encryptor = require('simple-encryptor')(key); 3 | 4 | 5 | const realString = "iloveu"; 6 | 7 | const encrypted = encryptor.encrypt(realString); 8 | console.log("encrypted message", encrypted); 9 | 10 | const decrypted = encryptor.decrypt(encrypted); 11 | console.log("decrypted message", decrypted); 12 | -------------------------------------------------------------------------------- /simple_express.js: -------------------------------------------------------------------------------- 1 | const bodyParser = require('body-parser'); 2 | const express = require('express'); 3 | const cors = require('cors'); 4 | 5 | const app = express(); 6 | 7 | app.use(bodyParser.json()); 8 | app.use(cors()); 9 | 10 | app.get('/', (req, res) => { 11 | res.send('success!'); 12 | }); 13 | 14 | app.listen(3000, () => 15 | console.log('app started - go to http://localhost:3000/') 16 | ); 17 | -------------------------------------------------------------------------------- /simple_webserver.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | 3 | const server = http.createServer(function (req, res) { 4 | if (req.url == '/') { 5 | 6 | res.writeHead(200, { 'Content-Type': 'text/html' }); 7 | 8 | res.write(` 9 | 10 | 11 |

Yeay Its Work

12 | 13 | `); 14 | 15 | res.end(); 16 | } 17 | 18 | }); 19 | 20 | server.listen(9000); 21 | 22 | console.log('Node.js web server at port 5000 is running..') -------------------------------------------------------------------------------- /streamPendingTransactions.js: -------------------------------------------------------------------------------- 1 | const ethers = require("ethers"); 2 | const url = "ADD_YOUR_ETHEREUM_NODE_WSS_URL"; 3 | 4 | const init = function () { 5 | const customWsProvider = new ethers.providers.WebSocketProvider(url); 6 | 7 | customWsProvider.on("pending", (tx) => { 8 | customWsProvider.getTransaction(tx).then(function (transaction) { 9 | console.log(transaction); 10 | }); 11 | }); 12 | 13 | customWsProvider._websocket.on("error", async () => { 14 | console.log(`Unable to connect to ${ep.subdomain} retrying in 3s...`); 15 | setTimeout(init, 3000); 16 | }); 17 | customWsProvider._websocket.on("close", async (code) => { 18 | console.log( 19 | `Connection lost with code ${code}! Attempting reconnect in 3s...` 20 | ); 21 | customWsProvider._websocket.terminate(); 22 | setTimeout(init, 3000); 23 | }); 24 | }; 25 | 26 | init(); 27 | -------------------------------------------------------------------------------- /string-to-base64.js: -------------------------------------------------------------------------------- 1 | const btoa = str => Buffer.from(str, 'binary').toString('base64'); 2 | 3 | // btoa('foobar'); // 'Zm9vYmFy' 4 | -------------------------------------------------------------------------------- /sugengenjing.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3000 4 | 5 | app.get('/', (req, res) => { 6 | res.send('Hello World!') 7 | }) 8 | 9 | app.listen(port, () => { 10 | console.log(`Example app listening at http://localhost:${port}`) 11 | }) 12 | -------------------------------------------------------------------------------- /tiktok.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios'); 2 | const cheerio = require('cheerio'); 3 | 4 | async function tiktokDown (Url) { 5 | return new Promise (async (resolve, reject) => { await axios.request({ 6 | url: "https://ttdownloader.com/", 7 | method: "GET", 8 | headers: { 9 | "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", 10 | "accept-language": "en-US,en;q=0.9,id;q=0.8", 11 | "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", 12 | "cookie": "_ga=GA1.2.1240046717.1620835673; PHPSESSID=i14curq5t8omcljj1hlle52762; popCookie=1; _gid=GA1.2.1936694796.1623913934" 13 | } 14 | }).then(respon => { 15 | const $ = cheerio.load(respon.data) 16 | const token = $('#token').attr('value') 17 | axios({ 18 | url: "https://ttdownloader.com/req/", 19 | method: "POST", 20 | data: new URLSearchParams(Object.entries({url: Url, format: "", token: token})), 21 | headers: { 22 | "accept": "*/*", 23 | "accept-language": "en-US,en;q=0.9,id;q=0.8", 24 | "content-type": "application/x-www-form-urlencoded; charset=UTF-8", 25 | "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36", 26 | "cookie": "_ga=GA1.2.1240046717.1620835673; PHPSESSID=i14curq5t8omcljj1hlle52762; popCookie=1; _gid=GA1.2.1936694796.1623913934" 27 | } 28 | }).then(res => { 29 | const ch = cheerio.load(res.data) 30 | var creator = `lala` 31 | const result = { 32 | status: res.status, 33 | author: `${creator}`, 34 | result: { 35 | nowatermark: ch('#results-list > div:nth-child(2)').find('div.download > a').attr('href'), 36 | watermark: ch('#results-list > div:nth-child(3)').find('div.download > a').attr('href'), 37 | audio: ch('#results-list > div:nth-child(4)').find(' div.download > a').attr('href') 38 | } 39 | } 40 | resolve(result) 41 | }).catch(reject) 42 | }).catch(reject) 43 | }) 44 | } 45 | 46 | module.exports = { tiktokDown} 47 | -------------------------------------------------------------------------------- /titleCase.js: -------------------------------------------------------------------------------- 1 | const titleCase = (word = '') => { 2 | let string = word.split(' '); 3 | let result = []; 4 | string.forEach((item, idx) => { 5 | const first = string[idx].slice(0,1).toLocaleUpperCase(); 6 | result.push(`${first}${item.substring(1)}`); 7 | }); 8 | return result.toString().replace(',', ' '); 9 | } 10 | 11 | console.log(titleCase('hacktoberfest hacktoberfest')); -------------------------------------------------------------------------------- /twitter.js: -------------------------------------------------------------------------------- 1 | // Our Twitter library 2 | const Twit = require("twit"); 3 | 4 | // We need to include our configuration file 5 | const twit = new Twit(require("./config.js")); 6 | 7 | // This is the URL of a search for the latest tweets on the '#MeetMaye' hashtag. 8 | const mediaArtsSearch = { q: "#MeetMaye", count: 100, result_type: "recent" }; 9 | 10 | // This function finds the latest tweet with the MeetMaye hashtag and retweets. 11 | const retweetLatest = () => { 12 | twit.get("search/tweets", mediaArtsSearch, (error, data) => { 13 | // log out any errors and responses 14 | console.log(error, data); 15 | // If our search request to the server had no errors... 16 | if (!error) { 17 | // ...then we grab the ID of the tweet we want to retweetwit... 18 | let retweetId = data.statuses[0].id_str; 19 | // ...and then we tell Twitter we want to retweet it! 20 | twit.post("statuses/retweet/" + retweetId, {}, (error, response) => { 21 | if (response) { 22 | console.log( 23 | "Success! Check your bot, it should have retweeted something." 24 | ); 25 | } 26 | // If there was an error with our Twitter call, we print it out here. 27 | if (error) { 28 | console.log("There was an error with Twitter:", error); 29 | } 30 | }); 31 | } 32 | // However, if our original search request had an error, we want to print it out here. 33 | else { 34 | console.log("There was an error with your hashtag search:", error); 35 | } 36 | }); 37 | } 38 | 39 | // Try to retweet something as soon as we run the program... 40 | retweetLatest(); 41 | // ...and then every hour/half thereafter. Time here is in milliseconds, so 42 | // 1000 ms = 1 second, 1 sec * 60 = 1 min, 1 min * 60 = 1 hour --> 1000 * 60 * 60 43 | setInterval(retweetLatest, 1000 * 60 * 30); 44 | -------------------------------------------------------------------------------- /two-sum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums e.g. [2,7,11,15] 3 | * @param {number} target e.g. 9 4 | * @return {number[]} returns an indexes of it e.g. [0, 1] 5 | */ 6 | var twoSum = function (nums, target) { 7 | const dict = {} 8 | for (let i = 0; i < nums.length; i++) { 9 | if (dict[nums[i]] === undefined) { 10 | dict[target - nums[i]] = i 11 | } else { 12 | return [dict[nums[i]], i] 13 | } 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /voltex.js: -------------------------------------------------------------------------------- 1 | const readline = require('readline') 2 | const rl = readline.createInterface({ 3 | input: process.stdin, 4 | output: process.stdout 5 | }) 6 | 7 | function cashbackCounter(cb, price) { 8 | return 'Rp. ' + Number((cb / 100) * price).toLocaleString('id'); 9 | } 10 | 11 | rl.question('Price : ', (price) => { 12 | rl.question('Casback : ', (cashback) => { 13 | const result = cashbackCounter(cashback, price) 14 | console.log('================[ Cashbac Counter ]================'); 15 | console.log('Price : ', 'Rp.', Number(price).toLocaleString('id')); 16 | console.log('Cashback : ', cashback + '%'); 17 | console.log('Result : ', result) 18 | rl.close(); 19 | }); 20 | }); 21 | Footer 22 | © 2022 GitHub, Inc. 23 | Footer navigation 24 | Terms 25 | Privacy 26 | -------------------------------------------------------------------------------- /warifp.js: -------------------------------------------------------------------------------- 1 | console.log('Hello World'); -------------------------------------------------------------------------------- /ysl.js: -------------------------------------------------------------------------------- 1 | const brainly = require('brainly-scraper'); 2 | const readlineSync = require('readline-sync') 3 | 4 | const q = readlineSync.question("Masukkan pertanyaanmu?: ") 5 | ======= 6 | const q = readlineSync.question("Masukkan keyword: ") 7 | 8 | 9 | brainly(q).then(res => { 10 | console.log(res); 11 | }); 12 | --------------------------------------------------------------------------------