├── .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 |
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 | [](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('