├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assert-module ├── Readme.md └── code │ ├── assert-deep-equals.js │ ├── assert-equal.js │ ├── assert-match.js │ └── assert-ok.js ├── assets └── GitHub-Social.png ├── build.js ├── console-module ├── README.md └── code │ ├── basic-console-logging.js │ ├── logs-formatting.js │ └── measure-time-taken.js ├── errors-module ├── README.md └── code │ ├── assertion-error.js │ ├── range-error.js │ ├── reference-error.js │ └── type-error.js ├── fs-module ├── Readme.md └── code │ ├── activities.txt │ ├── copyFile.js │ ├── createDirectory.js │ ├── createFile.js │ ├── createSymlink.js │ ├── createTempDir.js │ ├── delete-me.txt │ ├── deleteDirectory.js │ ├── deleteFile.js │ ├── fileOwnership.js │ ├── filePermission.js │ ├── friends-copy.txt │ ├── friends.txt │ ├── from │ ├── copyA.txt │ ├── copyB.txt │ ├── move-me.txt │ └── symMe.txt │ ├── moveFile.js │ ├── ownership.txt │ ├── permission.txt │ ├── readFile.js │ ├── readSync.js │ ├── rename-me.txt │ ├── renameFile.js │ ├── tasks.txt │ ├── to │ ├── copyA.txt │ └── copyB.txt │ ├── updateFile.js │ └── watchFileChanges.js ├── http-module ├── Readme.md └── code │ ├── create-server.js │ ├── get-request.js │ ├── post-request.js │ ├── query-params.js │ ├── query-string.js │ ├── set-header.js │ └── write-head.js ├── https-module ├── Readme.md └── code │ ├── create-server.js │ ├── get-request.js │ ├── post-request.js │ └── url-request.js ├── netlify.toml ├── sequelize-module ├── Readme.md └── code │ ├── basicModelQuerying.js │ ├── defineModel.js │ └── setupConnection.js ├── src ├── configs │ └── modules.config.json ├── css │ └── features-template.css ├── scripts │ └── main.js └── templates │ ├── features-template.html │ ├── group-template.html │ └── topic-template.html └── url-module ├── Readme.md └── code ├── toString-and-Json.js ├── url-method.js └── using-url-properties.js /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #Ignore these sensitive files 2 | /https-module/code/key.pem 3 | /https-module/code/server.key 4 | /https-module/code/server.cert 5 | build -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | tapas.adhikary@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | tapas.adhikary@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Tapas Adhikary 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nodeX 2 | 3 |

4 | social 5 |

6 | 7 | `nodeX` is an `OpenSource` project to capture working code examples for various node.js modules. 8 | 9 | It is aimed to help Node.js developers with code examples. Please contribute to the project, whatever ways possible. 10 | 11 | Liked the motive? Please give a star(⭐) to the project. 12 | 13 | ## How to build a browser-based interface? 14 | 15 | Just run (node v18 version required): 16 | 17 | ```node build.js``` 18 | 19 | ## How to deploy live documentation app? 20 | 21 |
22 | 23 | ### With Netlify 24 |
25 | 26 | You just need to [Import an existing project from a Git repository](https://docs.netlify.com/welcome/add-new-site/) selecting the desired branch (i.e.: main). ***netlify.toml*** contains all the configuration to make your website available. 27 | 28 |
29 | 30 | ### Other platforms 31 |
32 | Feel free to contribute. 33 | 34 |
35 |
36 |
37 | 38 | 39 | 40 | 41 | ### Many Thanks to all the `Stargazers` who has supported this project with stars(⭐) 42 | 43 | [![Stargazers repo roster for @atapas/nodeX](https://reporoster.com/stars/atapas/nodeX)](https://github.com/atapas/nodeX/stargazers) 44 | 45 | ## ToC 46 | 47 | - [Node.js File System Module Code Examples](./fs-module) 48 | - [Node.js HTTP Module Code Example](./http-module) 49 | - [Node.js HTTPS Module Code Example](./https-module) 50 | - [Node.js URL Module Code Example](./url-module) 51 | - [Node.js Assert Module Code Example](./assert-module) 52 | - [Node.js Sequelize Module Code Example](./sequelize-module) 53 | - [Node.js Console Module Code Example](./console-module) 54 | - [Node.js Errors Module Code Example](./errors-module) 55 | -------------------------------------------------------------------------------- /assert-module/Readme.md: -------------------------------------------------------------------------------- 1 | ## Node.js Assert module code examples 2 | 3 | Find [example code](./code) for most frequent URL module operations in this module. 4 | 5 | ## ToC 6 | 7 | <= [Parent](../README.md) 8 | 9 | - [How to use the deep equals METHOD](./code/assert-deep-equals.js) 10 | - [How to use the equal METHOD](./code/assert-equal.js) 11 | - [How to use the match METHOD](./code/assert-match.js) 12 | - [How to use the ok METHOD](./code/assert-ok.js) 13 | -------------------------------------------------------------------------------- /assert-module/code/assert-deep-equals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * deepEquals assertion makes a deep validation over properties and values 3 | * there's also available notDeepEqual to make a falsy validation 4 | */ 5 | const { deepEqual } = require('assert'); 6 | 7 | 8 | const shouldNotRaiseAnErrorSinceUserBisEqualsUserA = () => { 9 | const userA = { name: 'yuri', email: 'yuri@some-email.com' }; 10 | const userB = Object.assign({}, userA); 11 | deepEqual(userA, userB); 12 | }; 13 | 14 | const shouldRaiseAnErrorSinceUserBDiffersInName = () => { 15 | const userA = { name: 'yuri', email: 'yuri@some-email.com' }; 16 | const userB = Object.assign({}, userA, { name: userA.name.toUpperCase() }); 17 | const message = 'should Raise An Error Since UserB Differs In Name'; 18 | deepEqual(userA, userB, message); 19 | }; 20 | 21 | const shouldRaiseAnErrorSinceUserBDiffersInProperties = () => { 22 | const userA = { name: 'yuri', email: 'yuri@some-email.com' }; 23 | const userB = { name: 'yuri' }; 24 | const message = 'should Raise An Error Since UserB Differs In Properties'; 25 | deepEqual(userA, userB, message); 26 | }; 27 | 28 | const shouldRaiseAnErrorSinceUserBDiffersInInnerObjects = () => { 29 | const userA = { name: 'yuri', email: 'yuri@some-email.com', address: { city: { name: 'some name' } } }; 30 | const userB = Object.assign({}, userA, { address: { city: {} } }); 31 | const message = 'should Raise An Error Since UserB Differs In Inner Objects'; 32 | deepEqual(userA, userB, message); 33 | }; 34 | 35 | 36 | /** 37 | * execution goes here. the first example will not raise an error, 38 | * the other ones are handled since the first error will halt the 39 | * application execution 40 | */ 41 | shouldNotRaiseAnErrorSinceUserBisEqualsUserA(); 42 | 43 | try { 44 | shouldRaiseAnErrorSinceUserBDiffersInName(); 45 | } catch ({ message }) { 46 | console.log(message); 47 | } 48 | 49 | try { 50 | shouldRaiseAnErrorSinceUserBDiffersInProperties(); 51 | } catch ({ message }) { 52 | console.log(message); 53 | } 54 | 55 | try { 56 | shouldRaiseAnErrorSinceUserBDiffersInInnerObjects(); 57 | } catch ({ message }) { 58 | console.log(message); 59 | } 60 | -------------------------------------------------------------------------------- /assert-module/code/assert-equal.js: -------------------------------------------------------------------------------- 1 | /** 2 | * equal assertion makes a simple validation over primitive types 3 | * there's also available notEqual to make a falsy validation 4 | */ 5 | const { equal } = require('assert'); 6 | 7 | 8 | const shouldNotRaiseAnErrorSinceMessageBisEqualsMessageA = () => { 9 | const messageA = 'simple message'; 10 | const messageB = 'simple message'; 11 | equal(messageA, messageB); 12 | }; 13 | 14 | const shouldRaiseAnErrorSinceBothHasNotPrimitiveTypes = () => { 15 | const userA = { name: 'yuri' }; 16 | const userB = Object.assign({}, userA); 17 | const message = 'should Raise An Error Since Both Has Not Primitive Types'; 18 | equal(userA, userB, message); 19 | }; 20 | 21 | const shouldRaiseAnErrorSinceValueAisTrueAndValueBisFalse = () => { 22 | const valueA = true; 23 | const valueB = false; 24 | const message = 'should Raise An Error Since ValueA is True And ValueB is False'; 25 | equal(valueA, valueB, message); 26 | }; 27 | 28 | const shouldRaiseAnErrorSinceMessageBHasAnUppercaseLetter = () => { 29 | const messageA = 'simple message'; 30 | const messageB = 'Simple message'; 31 | const message = 'should Raise An Error Since messageB has an uppercase char'; 32 | equal(messageA, messageB, message); 33 | }; 34 | 35 | 36 | /** 37 | * execution goes here. the first example will not raise an error, 38 | * the other one is handled since the first error will halt the 39 | * application execution 40 | */ 41 | shouldNotRaiseAnErrorSinceMessageBisEqualsMessageA(); 42 | 43 | try { 44 | shouldRaiseAnErrorSinceMessageBHasAnUppercaseLetter(); 45 | } catch ({ message }) { 46 | console.log(message); 47 | } 48 | 49 | try { 50 | shouldRaiseAnErrorSinceValueAisTrueAndValueBisFalse(); 51 | } catch ({ message }) { 52 | console.log(message); 53 | } 54 | 55 | try { 56 | shouldRaiseAnErrorSinceBothHasNotPrimitiveTypes(); 57 | } catch ({ message }) { 58 | console.log(message); 59 | } 60 | -------------------------------------------------------------------------------- /assert-module/code/assert-match.js: -------------------------------------------------------------------------------- 1 | /** 2 | * match assertion makes a regex validation over an string value 3 | * there's also available doesNotMatch to make a falsy validation 4 | */ 5 | const { match } = require('assert'); 6 | 7 | 8 | const shouldNotRaiseAnErrorSinceEmailHasAnExpectedPattern = () => { 9 | const email = 'yuri@email.com'; 10 | const regex = /^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/i 11 | match(email, regex); 12 | }; 13 | 14 | const shouldRaiseAnErrorSinceEmailHasAnMismatchInPattern = () => { 15 | const email = 'yuriatemail.com'; 16 | const regex = /^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/i; 17 | const message = 'should Raise An Error Since Email Has An Mismatch In Pattern'; 18 | match(email, regex, message); 19 | }; 20 | 21 | 22 | /** 23 | * execution goes here. the first example will not raise an error, 24 | * the other one is handled since provided email has not an expected 25 | * pattern 26 | */ 27 | shouldNotRaiseAnErrorSinceEmailHasAnExpectedPattern(); 28 | 29 | try { 30 | shouldRaiseAnErrorSinceEmailHasAnMismatchInPattern(); 31 | } catch ({ message }) { 32 | console.log(message); 33 | } 34 | -------------------------------------------------------------------------------- /assert-module/code/assert-ok.js: -------------------------------------------------------------------------------- 1 | /** 2 | * ok assertion makes a simple truthy validation 3 | */ 4 | const { ok } = require('assert'); 5 | 6 | 7 | const shouldNotRaiseAnErrorSinceValueIsTruthy = () => { 8 | const value = 'some value'; 9 | ok(value); 10 | }; 11 | 12 | const shouldRaiseAnErrorSinceValueIsFalsy = () => { 13 | const value = !true; 14 | const message = 'should Raise An Error Since Value Is Falsy'; 15 | ok(value, message); 16 | }; 17 | 18 | /** 19 | * execution goes here. the first example will not raise an error, 20 | * the other one is handled since provided value is falsy 21 | */ 22 | shouldNotRaiseAnErrorSinceValueIsTruthy(); 23 | 24 | try { 25 | shouldRaiseAnErrorSinceValueIsFalsy(); 26 | } catch ({ message }) { 27 | console.log(message); 28 | } 29 | -------------------------------------------------------------------------------- /assets/GitHub-Social.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atapas/nodeX/47828ddb66ed63adf97a685183f4cf024f88dbf4/assets/GitHub-Social.png -------------------------------------------------------------------------------- /build.js: -------------------------------------------------------------------------------- 1 | /** 2 | * step 1: scan all folders with *-module pattern (OK) 3 | * 4 | * step 2: for each folder, do the following steps (conversion to html) 5 | * step 2.1: read each .js file and their content 6 | * step 2.2: generate some html for each file content 7 | * step 2.3: store there files references, nested into topic and files for each one 8 | * 9 | * step 3: with the topics stored, do the following steps: 10 | * step 3.1: generate an index.html file with "collapsing structure" (for each topic) 11 | * 12 | * step 4 (optional): do some grunt job to minify the html 13 | * 14 | * step 5: put on github ci to generate a github page 15 | */ 16 | const fs = require('fs'); 17 | const { readFile, writeFile, mkdir, rm, copyFile } = require('fs/promises'); 18 | 19 | 20 | const readAllJsFilesOnCodePath = async ({ path = '' }) => { 21 | const files = await fs.promises.readdir(`${path}/code`, (err, files = []) => { 22 | if (err) { throw new Error({ message: 'Unable to scan directory: ', err }) } 23 | const filenames = files.map(filename => `${path}/${filename}`); 24 | return filenames; 25 | }); 26 | return files 27 | .map(filename => `${path}/code/${filename}`) 28 | .filter((filepath = '') => filepath.endsWith('.js')); 29 | }; 30 | 31 | const getAllModuleDirectoriesOnPath = async ({ path = '' }) => { 32 | const files = await fs.promises.readdir(path, (err, files = []) => { 33 | if (err) { throw new Error({ message: 'Unable to scan directory: ', err }) } 34 | const filenames = files.map(filename => `${path}/${filename}`) 35 | return filenames 36 | }) || []; 37 | return files 38 | .filter(file => file.endsWith('-module')) 39 | .map(file => `${path}/${file}`); 40 | }; 41 | 42 | const getFeatures = async ({ folderPaths = [] }) => { 43 | const folderPromises = folderPaths.map(path => readAllJsFilesOnCodePath({ path })); 44 | const jsFilePaths = await (await Promise.all(folderPromises)) 45 | .flat(); 46 | return (await Promise.all(jsFilePaths.map(path => readFile(path, 'utf-8')))) 47 | .map((content, i) => { 48 | const path = jsFilePaths[i]; 49 | const regex = /(.+?)\/(\w+)-(module)\/code\/(.+?)\.js/i; 50 | const group = path.replace(regex, '$2'); 51 | const id = path 52 | .replace(regex, '$4') 53 | .replace(/([A-Z])/, '-$1') 54 | .toLowerCase(); 55 | const topic = path 56 | .replace(regex, '$4') 57 | .replace(/([A-Z])/, ' $1') 58 | .replace(/(\-)/, ' '); 59 | return { group, topic, html: content, id }; 60 | }); 61 | }; 62 | 63 | const getFeaturesWithFormattedTopics = async ({ features = [] }) => { 64 | const path = `${__dirname}/src/templates/topic-template.html`; 65 | const topicTemplate = await readFile(path, 'utf-8'); 66 | return features.map(feature => Object.assign({}, feature, { 67 | html: topicTemplate 68 | .replace(/{{ topicName }}/gmi, feature.topic) 69 | .replace(/{{ topicId }}/gmi, feature.id) 70 | })); 71 | } 72 | 73 | const getFeaturesWithFormattedGroups = async ({ featuresWithFormattedTopics = [] }) => { 74 | const path = `${__dirname}/src/templates/group-template.html`; 75 | const groupTemplate = await readFile(path, 'utf-8'); 76 | const uniqueGroups = featuresWithFormattedTopics 77 | .reduce((acc = [], { group }) => acc.includes(group) ? acc : [...acc, group], []); 78 | return uniqueGroups.map(uniqueGroup => { 79 | const groupFeatures = featuresWithFormattedTopics.filter(({ group }) => group === uniqueGroup); 80 | const featuresHtml = groupFeatures.map(({ html }) => html).join(''); 81 | const html = groupTemplate 82 | .replace(/{{ topics }}/gmi, featuresHtml) 83 | .replace(/{{ collapseTarget }}/gmi, `${uniqueGroup}-id`) 84 | .replace(/{{ groupName }}/mi, uniqueGroup); 85 | return html; 86 | }).join(''); 87 | } 88 | 89 | const getHtml = async ({ groupsHtml = '' }) => { 90 | const path = `${__dirname}/src/templates/features-template.html`; 91 | const featuresTemplate = await readFile(path, 'utf-8'); 92 | return featuresTemplate 93 | .replace(/{{ groups }}/gmi, groupsHtml) 94 | .replace(/..\/css\/features-template\.css/, 'styles.css') 95 | .replace(/..\/scripts\/main.js/, 'app.js'); 96 | } 97 | 98 | const getHtmlWithInjectedData = ({ features, html }) => { 99 | const topicsStr = JSON.stringify(features.map(({ id, html, topic }) => ({ id, html, topic }))); 100 | const data = `var data = ${topicsStr};`; 101 | return html.replace(/\/\/ {{ injectedData }}/, data); 102 | } 103 | 104 | const build = async ({ basePath, html }) => { 105 | const buildDir = `${basePath}/build`; 106 | const srcDir = `${basePath}/src`; 107 | const cssFilePath = `${srcDir}/css/features-template.css`; 108 | const scriptFilePath = `${srcDir}/scripts/main.js`; 109 | const filepath = `${buildDir}/index.html`; 110 | 111 | await rm(buildDir, { recursive: true, force: true }); 112 | 113 | try { await mkdir(buildDir); } catch (err) { console.log(err); } 114 | 115 | await copyFile(cssFilePath, `${buildDir}/styles.css`); 116 | await copyFile(scriptFilePath, `${buildDir}/app.js`); 117 | await writeFile(filepath, html); 118 | } 119 | 120 | const app = async () => { 121 | console.time('html-output'); 122 | const folderPaths = await getAllModuleDirectoriesOnPath({ path: __dirname }); 123 | const features = await getFeatures({ folderPaths }); 124 | const featuresWithFormattedTopics = await getFeaturesWithFormattedTopics({ features }) 125 | const groupsHtml = await getFeaturesWithFormattedGroups({ featuresWithFormattedTopics }) 126 | const html = await getHtml({ groupsHtml }); 127 | const injectedHtml = getHtmlWithInjectedData({ features, html }); 128 | await build({ basePath: __dirname, html: injectedHtml }); 129 | console.timeEnd('html-output'); 130 | } 131 | 132 | app(); 133 | -------------------------------------------------------------------------------- /console-module/README.md: -------------------------------------------------------------------------------- 1 | # Node.js Console module Code Examples 2 | 3 | Find [example code](./code) for most frequent Console module operations. Node.JS Console module provides methods for writing into streams. 4 | 5 | ## ToC 6 | 7 | <= [Parent](../README.md) 8 | 9 | - [How to write logs to a file?](./code/basic-console-logging.js) 10 | - [How to measure time taken to execute a block?](./code//measure-time-taken.js) 11 | - [How to format differently?](./code//logs-formatting.js) 12 | -------------------------------------------------------------------------------- /console-module/code/basic-console-logging.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Node.JS Console Module 3 | * 4 | * Save logs to output.log file, but send error logs to console. 5 | */ 6 | 7 | const { Console } = require('console'); 8 | const { createWriteStream } = require('fs'); 9 | 10 | const output = createWriteStream('./output.log'); 11 | 12 | const logger = new Console({ 13 | stdout: output, 14 | stderr: process.stdout 15 | }) 16 | 17 | 18 | let count = 0; 19 | const startLogging = new Promise((resolve, reject) => { 20 | // log a message for every half second 21 | const log = setInterval(() => { 22 | logger.log('Count at %s is %d', new Date(), ++count) 23 | }, 500); 24 | 25 | // log an error for every 2 seconds 26 | const err = setInterval(() => { 27 | logger.error('Logged error at %s', new Date()) 28 | }, 2000); 29 | 30 | // stop logging after 10 seconds 31 | const timeout = setTimeout(() => { 32 | clearInterval(log); 33 | clearInterval(err); 34 | 35 | resolve(timeout); 36 | }, 10000) 37 | }); 38 | 39 | startLogging.then(timeout => { 40 | clearTimeout(timeout) 41 | }) 42 | -------------------------------------------------------------------------------- /console-module/code/logs-formatting.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Node.JS Console Module 3 | * 4 | * Log the time taken of a async or time taking process 5 | */ 6 | const { Console } = require('console'); 7 | const { createWriteStream } = require('fs'); 8 | 9 | const output = createWriteStream('./output.log'); 10 | 11 | const logger = new Console({ stdout: output }) 12 | 13 | // Logging into tabular format ---------------------- 14 | 15 | // Log object in tabular form 16 | logger.table({ 17 | name: 'ArunKumar', 18 | favNo: 7, 19 | loves: ['JavaScript', 'Java', 'Python'] 20 | }) 21 | 22 | // Log array of strings in tabular form 23 | logger.table(['JavaScript', 'JS', 'ES6', 'TS']) 24 | 25 | // logg array of ambiguous data 26 | logger.table([ 27 | 'JS', 100, true, { 28 | n1: 23, n2: [1, 2, 3] 29 | } 30 | ]) 31 | 32 | logger.log('') 33 | 34 | // Grouping multiple logs ---------------------- 35 | logger.group('my-log-group'); 36 | logger.log('Hello') 37 | logger.error('Error') 38 | logger.info('Info') 39 | logger.log({ a: 1, b: 2 }) 40 | logger.groupEnd('my-log-group'); 41 | logger.log("I'll log out of group"); 42 | -------------------------------------------------------------------------------- /console-module/code/measure-time-taken.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Node.JS Console Module 3 | * 4 | * Log the time taken of a async or time taking process 5 | */ 6 | 7 | // Also works with global console 8 | const { time, timeEnd } = require('console'); 9 | const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); 10 | 11 | (async () => { 12 | time('measure-time-taken'); 13 | 14 | // Some time-taking process 15 | await delay(3000); 16 | 17 | timeEnd('measure-time-taken'); 18 | })() 19 | -------------------------------------------------------------------------------- /errors-module/README.md: -------------------------------------------------------------------------------- 1 | # Node.js Errors module Code Examples 2 | 3 | Find [example code](./code) for most frequent Errors module operations. Applications running in Node.js will generally experience four categories of errors. 4 | 5 | ## ToC 6 | 7 | <= [Parent](../README.md) 8 | 9 | - [AssertionError](./code/assertion-error.js) 10 | - [RangeError](./code/range-error.js) 11 | - [ReferenceError](./code/reference-error.js) 12 | - [TypeError](./code/type-error.js) -------------------------------------------------------------------------------- /errors-module/code/assertion-error.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Node.JS Errors Module 3 | * 4 | * All errors thrown by the node:assert module will be instances of the AssertionError class. 5 | */ 6 | 7 | const assert = require('assert'); 8 | 9 | var invalidNumber = function(){ 10 | throw console.log("Invalid Number"); 11 | }; 12 | 13 | var numberValidation = function(a){ 14 | if(a>10){ 15 | invalidNumber(); 16 | } 17 | else{ 18 | console.log("Valid number"); 19 | } 20 | }; 21 | 22 | assert.throws(function(){ 23 | numberValidation(5); 24 | }); 25 | -------------------------------------------------------------------------------- /errors-module/code/range-error.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Node.JS Errors Module 3 | * 4 | * RangeError indicates that a provided argument was not within the range of acceptable values. 5 | */ 6 | 7 | // Infinite recursion - It will result in the RangeError 8 | 9 | function foo() { 10 | foo(); 11 | } 12 | 13 | foo(); 14 | -------------------------------------------------------------------------------- /errors-module/code/reference-error.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Node.JS Errors Module 3 | * 4 | * ReferenceError happens when a variable that doesn't exist in the current scope. 5 | */ 6 | 7 | // Variable that doesn't exist 8 | console.log(x); 9 | 10 | 11 | // Variable that hasn't yet been initialized 12 | console.log(y); 13 | const y = 10; 14 | -------------------------------------------------------------------------------- /errors-module/code/type-error.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Node.JS Errors Module 3 | * 4 | * TypeError happens when an operation could not be performed, due to value is not expected type. 5 | */ 6 | 7 | let number = 11; 8 | 9 | try { 10 | number.toUpperCase(); 11 | } catch (err) { 12 | console.log(err); 13 | }; 14 | -------------------------------------------------------------------------------- /fs-module/Readme.md: -------------------------------------------------------------------------------- 1 | # Node.js file system module Code Examples 2 | 3 | Find [example code](./code) for most frequent file system operations in this module. Most of the code examples use the `promise`-based APIs. 4 | 5 | ## ToC 6 | 7 | <= [Parent](../README.md) 8 | 9 | - [How to Create a file](./code/createFile.js) 10 | - [How to Read a file](./code/readFile.js) 11 | - [How to write a file](./code/createFile.js) 12 | - [How to move a file](./code/moveFile.js) 13 | - [How to copy file](./code/copyFile.js) 14 | - [How to copy multiple files](./code/copyFile.js) 15 | - [How to rename a file](./code/renameFile.js) 16 | - [How to delete a file](./code/deleteFile.js) 17 | - [How to change the file permission](./code/filePermission.js) 18 | - [How to change the file ownership](./code/fileOwnership.js) 19 | - [How to create a symlink](./code/createSymlink.js) 20 | - [How to watch on changes to a file](./code/watchFileChanges.js) 21 | - [How to handle errors](./code) 22 | - [How to perform the file operations in synchronous way](./code/readSync.js) 23 | - [How to create a directory](./code/createDirectory.js) 24 | - [How to create a temporary directory](./code/createTempDir.js) 25 | - [How to rename a directory](./code/renameFile.js) 26 | - [How to delete a directory](./code/deleteDirectory.js) 27 | -------------------------------------------------------------------------------- /fs-module/code/activities.txt: -------------------------------------------------------------------------------- 1 | Skiing -------------------------------------------------------------------------------- /fs-module/code/copyFile.js: -------------------------------------------------------------------------------- 1 | 2 | const { copyFile } = require('fs/promises'); 3 | 4 | const { join } = require('path'); 5 | 6 | async function copyAFile(from, to) { 7 | try { 8 | await copyFile(from, to); 9 | console.log(`Copied ${from} to ${to}`); 10 | } catch (err) { 11 | console.error(`Got an error trying to copy the file: ${err.message}`); 12 | } 13 | } 14 | 15 | async function copyAll(fromDir, toDir, filePaths) { 16 | return Promise.all(filePaths.map(filePath => { 17 | return copyAFile(join(fromDir, filePath), join(toDir, filePath)); 18 | })); 19 | } 20 | 21 | async function copyFiles(fromDir, toDir, filePaths) { 22 | try { 23 | await copyAll(fromDir, toDir, filePaths); 24 | console.log('Copied all files'); 25 | } catch(err) { 26 | console.error(`Got an error trying to copy the files: ${err.message}`); 27 | } 28 | 29 | } 30 | 31 | // copyFile('friends.txt', 'friends-copy.txt'); 32 | 33 | copyFiles('from', 'to', ['copyA.txt', 'copyB.txt']); 34 | 35 | 36 | -------------------------------------------------------------------------------- /fs-module/code/createDirectory.js: -------------------------------------------------------------------------------- 1 | const { mkdir } = require('fs/promises'); 2 | 3 | async function createDirectory(path) { 4 | try { 5 | await mkdir(path); 6 | console.log(`Created directory ${path}`); 7 | } catch (error) { 8 | console.error(`Got an error trying to create the directory: ${error.message}`); 9 | } 10 | } 11 | 12 | createDirectory('new-directory'); -------------------------------------------------------------------------------- /fs-module/code/createFile.js: -------------------------------------------------------------------------------- 1 | 2 | const { writeFile, appendFile, open } = require('fs/promises'); 3 | 4 | async function writeToFile(fileName, data) { 5 | try { 6 | await writeFile(fileName, data); 7 | console.log(`Wrote data to ${fileName}`); 8 | } catch (error) { 9 | console.error(`Got an error trying to write the file: ${error.message}`); 10 | } 11 | } 12 | 13 | // Create file using the appendFile method 14 | async function appendToFile(fileName, data) { 15 | try { 16 | await appendFile(fileName, data, { flag: 'w' }); 17 | console.log(`Appended data to ${fileName}`); 18 | } catch (error) { 19 | console.error(`Got an error trying to append the file: ${error.message}`); 20 | } 21 | } 22 | 23 | // Create file using the open method 24 | async function openFile(fileName, data) { 25 | try { 26 | const file = await open(fileName, 'w'); 27 | await file.write(data); 28 | console.log(`Opened file ${fileName}`); 29 | } catch (error) { 30 | console.error(`Got an error trying to open the file: ${error.message}`); 31 | } 32 | } 33 | 34 | 35 | 36 | // Replaces the content of the file, if the file exists. 37 | // If the file does not exist, it creates a new file. 38 | writeToFile('friends.txt', 'Bob'); 39 | 40 | // Create a file using the appendFile method 41 | appendToFile('activities.txt', 'Skiing'); 42 | 43 | // Create a file with the open method 44 | openFile('tasks.txt', 'Do homework'); 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /fs-module/code/createSymlink.js: -------------------------------------------------------------------------------- 1 | 2 | const { symlink } = require('fs/promises'); 3 | const { join } = require('path'); 4 | 5 | async function createSymlink(target, path, type) { 6 | try { 7 | await symlink(target, path, type); 8 | console.log(`Created symlink to ${target} at ${path}`); 9 | } catch (error) { 10 | console.error(`Got an error trying to create the symlink: ${error.message}`); 11 | } 12 | } 13 | 14 | createSymlink('join(__dirname, from, symMe.txt)', 'symLinkToFile', 'file'); 15 | -------------------------------------------------------------------------------- /fs-module/code/createTempDir.js: -------------------------------------------------------------------------------- 1 | const { mkdtemp } = require('fs/promises'); 2 | const { join } = require('path'); 3 | const { tmpdir } = require('os'); 4 | 5 | async function createTemporaryDirectory(fileName) { 6 | try { 7 | const tempDirectory = await mkdtemp(join(tmpdir(), fileName)); 8 | console.log(`Created temporary directory ${tempDirectory}`); 9 | } catch (error) { 10 | console.error(`Got an error trying to create the temporary directory: ${error.message}`); 11 | } 12 | } 13 | 14 | createTemporaryDirectory('node-temp-tapas-'); 15 | 16 | -------------------------------------------------------------------------------- /fs-module/code/delete-me.txt: -------------------------------------------------------------------------------- 1 | Delete me!!! -------------------------------------------------------------------------------- /fs-module/code/deleteDirectory.js: -------------------------------------------------------------------------------- 1 | const { rmdir } = require('fs/promises'); 2 | 3 | async function deleteDirectory(path) { 4 | try { 5 | await rmdir(path); 6 | console.log(`Deleted directory ${path}`); 7 | } catch (error) { 8 | console.error(`Got an error trying to delete the directory: ${error.message}`); 9 | } 10 | } 11 | 12 | deleteDirectory('new-directory-renamed'); -------------------------------------------------------------------------------- /fs-module/code/deleteFile.js: -------------------------------------------------------------------------------- 1 | const { unlink } = require('fs/promises'); 2 | 3 | async function deleteFile(filePath) { 4 | try { 5 | await unlink(filePath); 6 | console.log(`Deleted ${filePath}`); 7 | } catch (error) { 8 | console.error(`Got an error trying to delete the file: ${error.message}`); 9 | } 10 | } 11 | 12 | deleteFile('delete-me.txt'); 13 | -------------------------------------------------------------------------------- /fs-module/code/fileOwnership.js: -------------------------------------------------------------------------------- 1 | 2 | const { chown } = require('fs/promises'); 3 | 4 | async function changeOwnership(filePath, userId, groupId) { 5 | try { 6 | await chown(filePath, userId, groupId); 7 | console.log(`Changed ownership to ${userId}:${groupId} for ${filePath}`); 8 | } catch (error) { 9 | console.error(`Got an error trying to change ownership: ${error.message}`); 10 | } 11 | } 12 | 13 | changeOwnership('ownership.txt', 1000, 1010); -------------------------------------------------------------------------------- /fs-module/code/filePermission.js: -------------------------------------------------------------------------------- 1 | 2 | const { chmod } = require('fs/promises'); 3 | 4 | async function changePermission(filePath, permission) { 5 | try { 6 | await chmod(filePath, permission); 7 | console.log(`Changed permission to ${permission} for ${filePath}`); 8 | } catch (error) { 9 | console.error(`Got an error trying to change permission: ${error.message}`); 10 | } 11 | } 12 | 13 | changePermission('permission.txt', 0o400); -------------------------------------------------------------------------------- /fs-module/code/friends-copy.txt: -------------------------------------------------------------------------------- 1 | BobHarryHarry 2 | Harry -------------------------------------------------------------------------------- /fs-module/code/friends.txt: -------------------------------------------------------------------------------- 1 | BobHarryHarry 2 | HarryHarryHarryBobby -------------------------------------------------------------------------------- /fs-module/code/from/copyA.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atapas/nodeX/47828ddb66ed63adf97a685183f4cf024f88dbf4/fs-module/code/from/copyA.txt -------------------------------------------------------------------------------- /fs-module/code/from/copyB.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atapas/nodeX/47828ddb66ed63adf97a685183f4cf024f88dbf4/fs-module/code/from/copyB.txt -------------------------------------------------------------------------------- /fs-module/code/from/move-me.txt: -------------------------------------------------------------------------------- 1 | Will someone move me? -------------------------------------------------------------------------------- /fs-module/code/from/symMe.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atapas/nodeX/47828ddb66ed63adf97a685183f4cf024f88dbf4/fs-module/code/from/symMe.txt -------------------------------------------------------------------------------- /fs-module/code/moveFile.js: -------------------------------------------------------------------------------- 1 | const { rename } = require('fs/promises'); 2 | 3 | const { join } = require('path'); 4 | 5 | async function moveFile(from, to) { 6 | try { 7 | await rename(from, to); 8 | console.log(`Moved ${from} to ${to}`); 9 | } catch (error) { 10 | console.error(`Got an error trying to move the file: ${error.message}`); 11 | } 12 | } 13 | 14 | const fromPath = join(__dirname, "from", "move-me.txt"); 15 | const destPath = join(__dirname, "to", "move-me.txt"); 16 | 17 | moveFile(fromPath, destPath); 18 | 19 | // moveFile(destPath, fromPath); 20 | 21 | 22 | -------------------------------------------------------------------------------- /fs-module/code/ownership.txt: -------------------------------------------------------------------------------- 1 | My Ownership can be changed!!! -------------------------------------------------------------------------------- /fs-module/code/permission.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atapas/nodeX/47828ddb66ed63adf97a685183f4cf024f88dbf4/fs-module/code/permission.txt -------------------------------------------------------------------------------- /fs-module/code/readFile.js: -------------------------------------------------------------------------------- 1 | const { readFile } = require('fs/promises'); 2 | 3 | async function readThisFile(filePath) { 4 | try { 5 | const data = await readFile(filePath); 6 | console.log(data.toString()); 7 | } catch (error) { 8 | console.error(`Got an error trying to read the file: ${error.message}`); 9 | } 10 | } 11 | 12 | readThisFile('activities.txt'); 13 | readThisFile('friends.txt'); 14 | readThisFile('tasks.txt'); -------------------------------------------------------------------------------- /fs-module/code/readSync.js: -------------------------------------------------------------------------------- 1 | 2 | const { readFileSync } = require('fs'); 3 | 4 | function readFileSynchronously(path) { 5 | try { 6 | const data = readFileSync(path); 7 | console.log(data.toString()); 8 | } catch (error) { 9 | console.error(error); 10 | } 11 | } 12 | 13 | readFileSynchronously('activities.txt'); 14 | readFileSynchronously('friends.txt'); 15 | readFileSynchronously('tasks.txt'); -------------------------------------------------------------------------------- /fs-module/code/rename-me.txt: -------------------------------------------------------------------------------- 1 | I am going to get renamed!!! -------------------------------------------------------------------------------- /fs-module/code/renameFile.js: -------------------------------------------------------------------------------- 1 | const { rename } = require('fs/promises'); 2 | 3 | async function renameFile(from, to) { 4 | try { 5 | await rename(from, to); 6 | console.log(`Renamed ${from} to ${to}`); 7 | } catch (error) { 8 | console.error(`Got an error trying to rename the file: ${error.message}`); 9 | } 10 | } 11 | 12 | const oldName = "rename-me.txt"; 13 | const newName = "renamed.txt"; 14 | 15 | renameFile(oldName, newName); 16 | 17 | // renameFile('new-directory', 'new-directory-renamed'); -------------------------------------------------------------------------------- /fs-module/code/tasks.txt: -------------------------------------------------------------------------------- 1 | Do homework -------------------------------------------------------------------------------- /fs-module/code/to/copyA.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atapas/nodeX/47828ddb66ed63adf97a685183f4cf024f88dbf4/fs-module/code/to/copyA.txt -------------------------------------------------------------------------------- /fs-module/code/to/copyB.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atapas/nodeX/47828ddb66ed63adf97a685183f4cf024f88dbf4/fs-module/code/to/copyB.txt -------------------------------------------------------------------------------- /fs-module/code/updateFile.js: -------------------------------------------------------------------------------- 1 | const { appendFile } = require('fs/promises'); 2 | 3 | // Create file using the appendFile method 4 | async function updateFile(fileName, data) { 5 | try { 6 | await appendFile(fileName, data, { flag: 'a' }); 7 | console.log(`Appended data to ${fileName}`); 8 | } catch (error) { 9 | console.error(`Got an error trying to append the file: ${error.message}`); 10 | } 11 | } 12 | 13 | updateFile('friends.txt', 'Bobby'); 14 | 15 | // updateFile('permission.txt', 'Harry'); -------------------------------------------------------------------------------- /fs-module/code/watchFileChanges.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | 4 | function watchAFile(file) { 5 | fs.watch(file, (event, filename) => { 6 | if (filename) { 7 | console.log(`${filename} file Changed`); 8 | } 9 | }); 10 | } 11 | 12 | watchAFile('friends.txt'); -------------------------------------------------------------------------------- /http-module/Readme.md: -------------------------------------------------------------------------------- 1 | ## Node.js HTTP module code examples 2 | 3 | Find [example code](./code) for most frequent HTTP module operations in this module. 4 | 5 | ## ToC 6 | 7 | <= [Parent](../README.md) 8 | 9 | - [How to create a server](./code/create-server.js) 10 | - [How to send response a header to a request](./code/write-head.js) 11 | - [How to header value for implicit header](./code/set-header.js) 12 | - [How to read the query string](./code/query-string.js) 13 | - [How to split the query string](./code/query-params.js) 14 | - [How to create a GET request](./code/get-request.js) 15 | - [How to create a POST request](./code/post-request.js) -------------------------------------------------------------------------------- /http-module/code/create-server.js: -------------------------------------------------------------------------------- 1 | //HTTP is a built-in module that allows Node.js to transfer data over Hyper Text Transfer Protocol 2 | //A server can be created using the HTTP Module 3 | 4 | var http = require('http'); 5 | http.createServer(function (req, res) { 6 | res.write('Hello World!'); 7 | res.end(); 8 | }).listen(3000) -------------------------------------------------------------------------------- /http-module/code/get-request.js: -------------------------------------------------------------------------------- 1 | //Perform a GET request 2 | //HTTP module can be used to create client requests 3 | 4 | //A GET request can be performed in 2 ways, using the http.get() and http.request() 5 | //Difference is that the http.get() method sets the method to GET and calls req.end() automatically 6 | 7 | const http = require('http'); 8 | 9 | const options = { 10 | hostname: 'webcode.me', 11 | port: 80, 12 | path: '/', 13 | method: 'GET' 14 | }; 15 | 16 | const req = http.request(options, (res) => { 17 | console.log(`statusCode: ${res.statusCode}`); 18 | res.on('data', (d) => { 19 | process.stdout.write(d); 20 | }); 21 | }); 22 | 23 | req.on('error', (err) => { 24 | console.error(err); 25 | }); 26 | 27 | req.end(); -------------------------------------------------------------------------------- /http-module/code/post-request.js: -------------------------------------------------------------------------------- 1 | const http = require('http') 2 | let payload = JSON.stringify({ 3 | "name": "Harry", 4 | "age": 28 5 | }); 6 | let headers = { 7 | 'Content-Type': 'application/json', 8 | 'Content-Length': Buffer.byteLength(payload, 'utf8') 9 | }; 10 | 11 | let options = { 12 | host: 'httpbin.org', 13 | port: 80, 14 | path: '/post', 15 | method: 'POST', 16 | headers: headers 17 | }; 18 | 19 | let reqPost = http.request(options, (res) => { 20 | console.log("status code: ", res.statusCode); 21 | 22 | res.on('data', (chunks) => { 23 | 24 | process.stdout.write(chunks); 25 | }); 26 | }); 27 | 28 | reqPost.write(payload); 29 | reqPost.end(); 30 | 31 | reqPost.on('error', (err) => { 32 | 33 | console.error(err); 34 | }); -------------------------------------------------------------------------------- /http-module/code/query-params.js: -------------------------------------------------------------------------------- 1 | //URL is a built-in node.js module which is used to split up a web address into readable parts 2 | //url.parse() = parses an addrss with each part of the address as properties 3 | const http = require('http') 4 | const url = require('url') 5 | http.createServer(function (req, res) { 6 | let q = url.parse(req.url, true).query 7 | let message = 'Hello ' + q.name + '!' 8 | //try inserting a name and value in the URL 9 | res.writeHead(200, { 10 | 'Content-Type': 'text/html' 11 | }) 12 | res.write('

' + message + '

') 13 | res.end() 14 | }).listen(3000, function () { 15 | console.log('Server running on Port 3000') 16 | }) -------------------------------------------------------------------------------- /http-module/code/query-string.js: -------------------------------------------------------------------------------- 1 | const http = require('http') 2 | http.createServer(function (req, res) { 3 | if (req.url === '/') { 4 | res.writeHead(200, { 5 | 'Content-Type': 'text/html' 6 | }) 7 | res.write('

Hello, Home Page!

') 8 | res.end() 9 | } 10 | else if (req.url === '/example') { 11 | res.writeHead(200, { 12 | 'Content-Type': 'application/json' 13 | }) 14 | res.write(JSON.stringify({ 15 | 'Foo': 'Bar' 16 | })) 17 | res.end() 18 | } 19 | else { 20 | res.end('Invalid Request') 21 | } 22 | }).listen(3000, function () { 23 | console.log('Server running on Port 3000') 24 | }) -------------------------------------------------------------------------------- /http-module/code/set-header.js: -------------------------------------------------------------------------------- 1 | //Syntax = setHeader(name-of-the-header, value-of-the-header) 2 | //Purpose = used to set single header value for implicit headers 3 | 4 | const http = require('http') 5 | http.createServer(function (req, res) { 6 | res.setHeader('Content-Type', 'text/plain'); 7 | res.writeHead(200, { 8 | 'Content-Type': 'text/html' 9 | }) 10 | res.write('Hello Node.js!') 11 | res.end() 12 | }).listen(3000, function () { 13 | console.log('Server running on port 3000') 14 | }) 15 | 16 | //Here you can see that the text/plain in setHeader is overriden by that of text/html in writeHead 17 | //It can be concluded that writeHead() has precedence over setHeader() 18 | 19 | //If you write the setHeader() after the writeHead(), an error occurs 20 | //This is because headers cannot be set after they are sent to the client 21 | -------------------------------------------------------------------------------- /http-module/code/write-head.js: -------------------------------------------------------------------------------- 1 | const http = require('http') 2 | http.createServer(function (req, res) { 3 | res.writeHead(200, { 4 | 'Content-Type': 'application/json' 5 | }) 6 | res.write(JSON.stringify({ 7 | 'Name': 'John Doe', 8 | 'Age': '28' 9 | })) 10 | res.end() 11 | }).listen(3000, function () { 12 | console.log('Server running on Port 3000') 13 | }) 14 | -------------------------------------------------------------------------------- /https-module/Readme.md: -------------------------------------------------------------------------------- 1 | ## Node.js HTTPS module code examples 2 | 3 | Find [example code](./code) for most frequent HTTPS module operations in this module. 4 | 5 | ## ToC 6 | 7 | <= [Parent](../README.md) 8 | 9 | - [How to create a server](./code/create-server.js) 10 | - [How to create a GET request](./code/get-request.js) 11 | - [How to create a POST request](./code/post-request.js) 12 | - [How to get data from a given URL](./code/url-request.js) -------------------------------------------------------------------------------- /https-module/code/create-server.js: -------------------------------------------------------------------------------- 1 | const https = require('https') 2 | const fs = require('fs') 3 | const options = { 4 | key: fs.readFileSync("server.key"), 5 | cert: fs.readFileSync("server.cert"), 6 | }; 7 | https.createServer(options, function (req, res) { 8 | res.writeHead(200, { 9 | 'Content-Type': 'text/plain' 10 | }) 11 | res.end('Hello World') 12 | }).listen(3000) 13 | 14 | //Run the following commands before running this file. 15 | //command = openssl req - nodes - new - x509 - keyout server.key - out server.cert 16 | // After running this command, we would get some options to fill.We can keep those options default or empty by entering ‘.‘ (dot).We would fill only two options for current as that would work fine for us. 17 | // Common Name(e.g.server FQDN or your name): localhost 18 | // Email Address: *************@****** (enter your email) 19 | // Other options such as Country Name, State or Province Name, Locality Name, Organization Name, and Organizational Unit Name are self - explanatory and also the system gives their example for help. 20 | 21 | //It is necessary to generate these files 22 | //server.cert = self-signed certificate file 23 | //server.key = Private key of the certificate 24 | -------------------------------------------------------------------------------- /https-module/code/get-request.js: -------------------------------------------------------------------------------- 1 | const https = require('https') 2 | 3 | https.get('https://jsonplaceholder.typicode.com/users', (res) => { 4 | console.log('statusCode:', res.statusCode); 5 | console.log('headers:', res.headers); 6 | 7 | res.on('data', (d) => { 8 | process.stdout.write(d); 9 | }); 10 | 11 | }).on('error', (e) => { 12 | console.error(e); 13 | }); -------------------------------------------------------------------------------- /https-module/code/post-request.js: -------------------------------------------------------------------------------- 1 | const https = require('https'); 2 | 3 | const data = JSON.stringify({ 4 | name: 'John Doe', 5 | job: 'Content Writer' 6 | }); 7 | 8 | const options = { 9 | hostname: 'jsonplaceholder.typicode.com', 10 | path: '/users', 11 | method: 'POST', 12 | headers: { 13 | 'Content-Type': 'application/json', 14 | 'Content-Length': data.length 15 | } 16 | }; 17 | 18 | const req = https.request(options, (res) => { 19 | let data = ''; 20 | console.log('Status Code:', res.statusCode); 21 | res.on('data', (d) => { 22 | data = data + d; 23 | }); 24 | res.on('end', () => { 25 | console.log('Body: ', JSON.parse(data)); 26 | }); 27 | }) 28 | 29 | req.on("error", (err) => { 30 | console.log("Error: ", err.message); 31 | }); 32 | 33 | req.write(data); 34 | req.end(); -------------------------------------------------------------------------------- /https-module/code/url-request.js: -------------------------------------------------------------------------------- 1 | const https = require('https') 2 | 3 | const url = 'https://jsonplaceholder.typicode.com/users' 4 | 5 | const req = https.request(url, (res) => { 6 | let data = '' 7 | res.on('data', (d) => { 8 | data = data + d; 9 | }) 10 | res.on('end', () => { 11 | console.log(JSON.parse(data)) 12 | }) 13 | }) 14 | 15 | req.on('error', (err) => { 16 | console.log(err) 17 | }) 18 | 19 | req.end() -------------------------------------------------------------------------------- /netlify.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | 3 | base = "." 4 | publish = "build/" 5 | command = "node build.js" 6 | 7 | [[redirects]] 8 | 9 | from = "/*" 10 | to = "/index.html" 11 | status = 200 12 | -------------------------------------------------------------------------------- /sequelize-module/Readme.md: -------------------------------------------------------------------------------- 1 | ## sequelize ORM 2 | 3 | sequelize is an ORM framework to execute RDBMS queries from your NodeJS application to the database. 4 | 5 | ## How to install sequelize and RDBMS associated driver 6 | 7 | To install the sequelize dependency run the following command: 8 | npm i sequelize 9 | 10 | To install the required RDBMS driver (here taking mysql as example) run the following command: 11 | npm i mysql2 12 | 13 | ## Node.js sequelize module code examples 14 | 15 | Find [example code](./code/setupConnection.js) for most creating a connection to database using this module. 16 | 17 | ## ToC 18 | 19 | <= [Parent](./Readme.md) 20 | 21 | - [How to setup a connection](./code/setupConnection.js) 22 | - [How to define a model](./code/defineModel.js) 23 | - [How to run basic querying examples](./code/basicModelQuerying.js) -------------------------------------------------------------------------------- /sequelize-module/code/basicModelQuerying.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @Description : Suppose we need to find out the category from the category table whose id is either 2 or 5 then that 3 | * can be done by running the following command 4 | */ 5 | 6 | category.findAll({ 7 | where:{ 8 | Id:{ 9 | [Op.or]:[2,5] 10 | } 11 | }) 12 | 13 | 14 | /* 15 | * @description :suppose we need to find out all the categories whose id is neither 1,2 or 3 and contains a substring 16 | * `product` in its description then the script will be: 17 | */ 18 | 19 | category.findAll({ 20 | where: { 21 | [Op.and]: 22 | { Id:{ 23 | [Op.gt]:3 } 24 | }, { 25 | description:{ 26 | [Op.substring]:’product’ 27 | } } } }) -------------------------------------------------------------------------------- /sequelize-module/code/defineModel.js: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * @description : provided an example to create a table named "categories" with columns : id, name and description 4 | * 5 | */ 6 | 7 | const Category = sequelize.define("category", { 8 | id: { 9 | type: Sequelize.INTEGER, 10 | primaryKey: true, 11 | autoIncrement: true 12 | }, 13 | name: { 14 | type: Sequelize.STRING, 15 | allowNull: false 16 | }, 17 | description: { 18 | type: Sequelize.STRING 19 | }, 20 | },{ 21 | tableName: 'categories' 22 | /** 23 | * This helps you to provie a custom name to the table 24 | * If above is not provided, model name is converted into 25 | plural and set as the table name 26 | * 27 | * If we want to just use the model name provided, we can 28 | provide the below option : 29 | * 30 | * freezeTableName: true 31 | */ 32 | }); 33 | return Category; 34 | -------------------------------------------------------------------------------- /sequelize-module/code/setupConnection.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @description : The Sequelize function in sequelize module is used to create an instance to connect with database. 3 | * authenticate function authenticates the database with provided value, if not returns an error. 4 | * sync function when called, authenticates and create connection first by calling the createConnection(), 5 | * then if successfull, runs the callback function 6 | */ 7 | 8 | const { Sequelize } = require("sequelize"); 9 | function createConnection() { 10 | 11 | let sequelize = new Sequelize('', '', '', { 12 | host: 'localhost', 13 | dialect: 'mysql', 14 | }); 15 | 16 | sequelize.authenticate().then(() => { 17 | console.log('connected successfully'); 18 | }).catch((error) => { 19 | console.log("error occurred"); 20 | }); 21 | 22 | return { sequelize } 23 | 24 | } 25 | 26 | let { sequelize } = createConnection(); 27 | 28 | function executeWithSync(promiseCallback) { 29 | sequelize.sync().then(() => promiseCallback); 30 | } 31 | 32 | module.exports = { sequelize, executeWithSync }; -------------------------------------------------------------------------------- /src/configs/modules.config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "fs", 4 | "icon": "" 5 | }, 6 | { 7 | "assert": "fs", 8 | "icon": "" 9 | }, 10 | { 11 | "name": "http", 12 | "icon": "" 13 | }, 14 | { 15 | "name": "https", 16 | "icon": "" 17 | }, 18 | { 19 | "name": "default", 20 | "icon": "" 21 | }, 22 | { 23 | "name": "url", 24 | "icon": "" 25 | } 26 | ] -------------------------------------------------------------------------------- /src/css/features-template.css: -------------------------------------------------------------------------------- 1 | .feature-icon { 2 | width: 4rem; 3 | height: 4rem; 4 | border-radius: .75rem; 5 | } 6 | 7 | .icon-link>.bi { 8 | margin-top: .125rem; 9 | margin-left: .125rem; 10 | fill: currentcolor; 11 | transition: transform .25s ease-in-out; 12 | } 13 | 14 | .icon-link:hover>.bi { 15 | transform: translate(.25rem); 16 | } 17 | 18 | .icon-square { 19 | width: 3rem; 20 | height: 3rem; 21 | border-radius: .75rem; 22 | } 23 | 24 | .text-shadow-1 { 25 | text-shadow: 0 .125rem .25rem rgba(0, 0, 0, .25); 26 | } 27 | 28 | .text-shadow-2 { 29 | text-shadow: 0 .25rem .5rem rgba(0, 0, 0, .25); 30 | } 31 | 32 | .text-shadow-3 { 33 | text-shadow: 0 .5rem 1.5rem rgba(0, 0, 0, .25); 34 | } 35 | 36 | .card-cover { 37 | background-repeat: no-repeat; 38 | background-position: center center; 39 | background-size: cover; 40 | } 41 | 42 | .feature-icon-small { 43 | width: 3rem; 44 | height: 3rem; 45 | } 46 | 47 | .bd-placeholder-img { 48 | font-size: 1.125rem; 49 | text-anchor: middle; 50 | -webkit-user-select: none; 51 | -moz-user-select: none; 52 | user-select: none; 53 | } 54 | 55 | @media (min-width: 768px) { 56 | .bd-placeholder-img-lg { 57 | font-size: 3.5rem; 58 | } 59 | } 60 | 61 | .b-example-divider { 62 | height: 3rem; 63 | background-color: rgba(0, 0, 0, .1); 64 | border: solid rgba(0, 0, 0, .15); 65 | border-width: 1px 0; 66 | box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15); 67 | } 68 | 69 | .b-example-vr { 70 | flex-shrink: 0; 71 | width: 1.5rem; 72 | height: 100vh; 73 | } 74 | 75 | .bi { 76 | vertical-align: -.125em; 77 | fill: currentColor; 78 | } 79 | 80 | .nav-scroller { 81 | position: relative; 82 | z-index: 2; 83 | height: 2.75rem; 84 | overflow-y: hidden; 85 | } 86 | 87 | .nav-scroller .nav { 88 | display: flex; 89 | flex-wrap: nowrap; 90 | padding-bottom: 1rem; 91 | margin-top: -1px; 92 | overflow-x: auto; 93 | text-align: center; 94 | white-space: nowrap; 95 | -webkit-overflow-scrolling: touch; 96 | } 97 | 98 | #custom-cards { 99 | padding: 0 !important; 100 | } 101 | 102 | .topic-card { 103 | background: darkslategrey; 104 | transition: background 0.5s ease-in-out; 105 | } 106 | 107 | .topic-card:hover { 108 | background: rgb(42, 36, 82); 109 | -webkit-transform: scale(1.1); 110 | } -------------------------------------------------------------------------------- /src/scripts/main.js: -------------------------------------------------------------------------------- 1 | const openDialog = ({ html = '', topic = '' }) => { 2 | console.log(html) 3 | const highlightedHtml = `
${Prism.highlight(html, Prism.languages.javascript, 'javascript')}
`; 4 | 5 | document.getElementById('modalTitle').innerHTML = `module - ${topic}`.toUpperCase(); 6 | document.getElementById('modalContent').innerHTML = highlightedHtml; 7 | const options = {}; 8 | const modal = new bootstrap.Modal(document.getElementById('staticBackdropModal'), options); 9 | modal.show(); 10 | } 11 | 12 | window.onload = () => { 13 | const groups = document.querySelectorAll('.module-row'); 14 | const topicCards = document.querySelectorAll('.topic-card'); 15 | 16 | groups.forEach(group => { 17 | group.addEventListener('click', (el) => { 18 | const { currentTarget } = el; 19 | const [collapseButton] = currentTarget.getElementsByClassName('btn btn-link'); 20 | collapseButton.click(); 21 | }); 22 | }); 23 | 24 | topicCards.forEach(topic => { 25 | topic.addEventListener('click', (el) => { 26 | const { currentTarget: { id: currentId } = {} } = el; 27 | const { html, topic } = data.find(({ id }) => id === currentId); 28 | openDialog({ html, topic }); 29 | }); 30 | }); 31 | }; 32 | -------------------------------------------------------------------------------- /src/templates/features-template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | NodeX Project 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | Bootstrap 31 | 33 | 34 | 35 | 36 | 38 | 39 | 40 | 42 | 44 | 45 | 46 | 48 | 49 | 50 | 51 | 53 | 54 | 55 | 57 | 58 | 59 | 61 | 62 | 63 | 65 | 67 | 68 | 69 | 71 | 72 | 73 | 74 | 76 | 77 | 78 | 80 | 81 | 82 | 84 | 86 | 87 | 88 | 89 | 91 | 92 | 93 | 94 | 96 | 97 | 98 | 100 | 101 | 102 | 104 | 105 | 106 | 107 |
108 | {{ groups }} 109 |
110 | 111 | 112 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /src/templates/group-template.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

Module: {{ groupName }} 5 |

6 | 19 |
20 | 21 | 22 |
23 | {{ topics }} 24 |
25 |
-------------------------------------------------------------------------------- /src/templates/topic-template.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |

{{ topicName }}

5 | 22 |
23 |
24 |
-------------------------------------------------------------------------------- /url-module/Readme.md: -------------------------------------------------------------------------------- 1 | ## Node.js URL module code examples 2 | 3 | Find [example code](./code) for most frequent URL module operations in this module. 4 | 5 | ## ToC 6 | 7 | <= [Parent](../README.md) 8 | 9 | - [How to use the URL METHOD](./code/url-method.js) 10 | - [How to use the URL module properties](./code/using-url-properties.js) 11 | - [ToString and ToJson in URL module](./code/toString-and-Json.js) 12 | -------------------------------------------------------------------------------- /url-module/code/toString-and-Json.js: -------------------------------------------------------------------------------- 1 | //The output of the URL method can be convertd toString or toJSON 2 | 3 | const newUrl = new URL( 4 | "https://blog.typicode.com/husky-git-hooks-autoinstall/search?articleID=1" 5 | ); 6 | const anotherUrl = new URL("http://localhost:5000/api/v1/search?author=Vick"); 7 | 8 | //toString 9 | console.log(newUrl.toString()); 10 | console.log(anotherUrl.toString()); 11 | 12 | console.log("-------------------------------------"); 13 | 14 | //toJSON 15 | console.log(newUrl.toJSON()); 16 | console.log(anotherUrl.toJSON()); 17 | -------------------------------------------------------------------------------- /url-module/code/url-method.js: -------------------------------------------------------------------------------- 1 | //The URL Module breaks/splits a web address into readable parts. 2 | //It provides utilities for URL parsing and resolution 3 | 4 | const newUrl = new URL("https://jsonplaceholder.typicode.com"); 5 | console.log(newUrl); 6 | 7 | //The URL method accepts two argument: the url and options. Logging the contents of the method to the console gives a JSON that has all the properties of the url. 8 | -------------------------------------------------------------------------------- /url-module/code/using-url-properties.js: -------------------------------------------------------------------------------- 1 | //The host and hostname of a url can be gotten using the URL module 2 | 3 | const newUrl = new URL( 4 | "https://blog.typicode.com/husky-git-hooks-autoinstall/search?articleID=1" 5 | ); 6 | const anotherUrl = new URL("http://localhost:5000/api/v1/search?author=Vick"); 7 | 8 | //Host 9 | //Specifies the host of a url 10 | 11 | console.log(newUrl.host); //=> blog.typicode.com 12 | console.log(anotherUrl.host); 13 | //Hostname 14 | //Specifies the hostname of a url 15 | console.log(newUrl.hostname); //=>blog.typicode.com 16 | console.log(anotherUrl.hostname); 17 | //Path 18 | //To output the appended path to the host/hostname 19 | console.log(newUrl.pathname); //Outputs => /husky-git-hooks-autoinstall/ 20 | console.log(anotherUrl.pathname); 21 | 22 | //Protocol 23 | //Specifies the url's protocol either http or https 24 | console.log(newUrl.protocol); //Outputs => https: 25 | console.log(anotherUrl.protocol); 26 | //Port 27 | //Specifies the port the url is running on similar to the port created when creating a http server 28 | console.log(newUrl.port); //Outputs port number , e.g 5000,3000,etc 29 | console.log(anotherUrl.port); 30 | 31 | //Origin 32 | //Identifies the url's read-only origin 33 | console.log(newUrl.origin); //Outputs => https://blog.typicode.com 34 | console.log(anotherUrl.origin); 35 | 36 | //SearchParams 37 | //Identifies search parameters of a url 38 | console.log(newUrl.searchParams); //Outputs=> {articleID => 1} 39 | console.log(anotherUrl.searchParams); 40 | --------------------------------------------------------------------------------