├── .jshintrc
├── CONTRIBUTING.md
├── README.md
├── _config.yml
├── assets
├── NASA.mp4
├── child-process.png
├── event-loop.png
├── eventEmitter_works.png
├── eventemiitter.png
├── express-mw.png
├── file.json
├── memory-scheme.png
├── microservices-communication.png
├── monolithic-and-microservices-architecture.jpg
├── node-js-jwt-authentication-mysql-project-structure.png
├── nodejs-event-loop.png
├── nodejs_cluster.png
├── pm2-load-balancer.png
├── reactor-pattern.jpg
├── star.png
├── temp.txt
├── test.txt
└── testPyramid.png
├── important.md
├── jwt-asymmetric-cryptography-authentication
├── .gitignore
├── README.md
├── authServer.js
├── certs
│ ├── accessTokenPrivateKey.pem
│ ├── accessTokenPubliKey.pem
│ ├── refreshTokenPrivateKey.pem
│ └── refreshTokenPubliKey.pem
├── example.env
├── package-lock.json
├── package.json
├── requests.rest
└── server.js
├── jwt-authentication
├── .gitignore
├── README.md
├── authServer.js
├── example.env
├── package-lock.json
├── package.json
├── requests.rest
└── server.js
├── node-jwt-mysql-auth
├── .gitignore
├── README.md
├── app
│ ├── config
│ │ ├── auth.config.js
│ │ ├── db.config.js
│ │ └── testdb.sql
│ ├── controllers
│ │ ├── auth.controller.js
│ │ └── user.controller.js
│ ├── middleware
│ │ ├── authJwt.js
│ │ ├── index.js
│ │ └── verifySignUp.js
│ ├── models
│ │ ├── index.js
│ │ ├── role.model.js
│ │ └── user.model.js
│ └── routes
│ │ ├── auth.routes.js
│ │ └── user.routes.js
├── package.json
├── requests.rest
└── server.js
├── nodejs-api.md
├── nodejs-basics
├── .gitignore
├── assert.js
├── buffer.js
├── callback.js
├── child-process-support.js
├── child-process.js
├── console.js
├── create_directory.bat
├── crypto.js
├── debugger.js
├── dns.js
├── event.js
├── exception.js
├── exec.js
├── fs-module.js
├── global-objects.js
├── index.html
├── input.txt
├── miscellaneous.js
├── net-client.js
├── net-server.js
├── os.js
├── output.txt
├── package-lock.json
├── path.js
├── play-video.js
├── process.js
├── querystring.js
├── server.js
├── standard-input-output.js
├── stream.js
├── string-decoder.js
├── timmer.js
├── tls.js
├── v8.js
├── web-module.js
└── zlib.js
├── nodejs-commands.md
├── nodejs-mysql
├── .gitignore
├── alter-table.js
├── config.js
├── create-db.js
├── create-table.js
├── delete-record.js
├── insert-record.js
├── package-lock.json
├── select-record.js
└── update-record.js
└── nodejs-programming.md
/.jshintrc:
--------------------------------------------------------------------------------
1 | {
2 | "esversion": 6
3 | }
4 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Making contributions
2 |
3 | You've just gotten on this project and you're as excited as bells, yes?
4 | You'll want to chill a bit and do a bit of understanding guidelines on how you'll make commit messages. I've found commit messages to be very helpful as regards large projects or projects with more than one contributor.
5 | Also always add a new Question to the list of questions instead of updating the exiting one unless there's a typo.
6 |
7 | ### Let's Contribute 👍
8 |
9 | - **Step 1** - Fork this repository.
10 | - **Step 2** - Clone the repository to your local machine.
11 | - **Step 3** - Resolve the bugs, mentions provided in the Issues section of the repository. _Also add a description of what changes you have done_.
12 | - **Step 4** - Add the changes to your repository.
13 | - **Step 5** - Create a PULL Request. And that's all.
14 |
15 | ### What you can contribute in this repo? 👊
16 |
17 | - You can add a new nodejs interview question.
18 | - There are various topics like - Node Process Model , Node Crypto Module, Stubs in Node etc. **_You can contribute in them_**
19 | - You can contribute some **Learning Resources** in the **_Readme.md_** File.
20 | - You can modify previous solutions if you feel like your solution has better **_Time or Space complexity._**
21 | - If you find a typo in the code you can resolve them.
22 |
23 | ### How to begin
24 |
25 | The point of the commit message has to do with a prefix. Commit messages should be in the format:
26 | `[Commit type]: Message(Try to stay within 50 chars)`
27 |
28 | Where:
29 |
30 | - Commit type: refers to one of a predefined subset of what a commit could mean. The subsets are:
31 |
32 | - Feature: Involves adding a new feature to the product or an implementation of a specified feature.
33 | - Chore: For changes that do not add new functionality but simply denotes a task performed. Does not have to do with bug fixes. Changes includes: initializing a new project, addition of files, partial changes that do not cause bugs, updates, etc.
34 | - Bug: For changes fixing a bug, typo or anything that leads to correctness of the system being worked on
35 | - Buggy: Should be avoided as much as possible but could be needed. It is used when changes have been partially implemented and execution of the current state of the project would lead to evil bugs and sinister errors. An example refers to unclosed tags and a hurried commit since you might not get access to your PC for a while. Projects with this commit type as the latest one should perhaps not be pulled or cloned except such implementation is to be continued by you.
36 |
37 | - Message: refers to a message describing the changes made. It is important that each commit should only reflect one feature or implementation change. You should not cram two functionalities into one commit except they depend closely on one another. For example, implementation of auth and adding views for a user profile are closely related but do not inter-depend on one another and should be separated into different commits. This is just to ensure a dev could work with states that are narrowed down to specific implementations and features.
38 |
39 | ## FAQ
40 |
41 | - Must I do this: Yes
42 | - Why: Read up
43 | - What happens if I don't do it: Your pull request wont be merged to master branch.
44 | - Is this the best implementation there is: Nah, I don't think so. It is subject to review and subsequent update. For now, do this.
45 | - Has it worked so far: YEAH, I think so
46 | - What else: Nothing
47 |
48 | ### Got issues?
49 |
50 | Raise an issue
51 |
52 | ### Friend's not got issues?
53 |
54 | Cool still raise the issue.
55 |
56 | ##### Let's Contribute 🤗
57 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/assets/NASA.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/NASA.mp4
--------------------------------------------------------------------------------
/assets/child-process.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/child-process.png
--------------------------------------------------------------------------------
/assets/event-loop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/event-loop.png
--------------------------------------------------------------------------------
/assets/eventEmitter_works.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/eventEmitter_works.png
--------------------------------------------------------------------------------
/assets/eventemiitter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/eventemiitter.png
--------------------------------------------------------------------------------
/assets/express-mw.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/express-mw.png
--------------------------------------------------------------------------------
/assets/file.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "_id": "5d09c20f10f24cbe9f0fd63a",
4 | "name": "Hoover Sheppard"
5 | }
6 | ]
7 |
--------------------------------------------------------------------------------
/assets/memory-scheme.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/memory-scheme.png
--------------------------------------------------------------------------------
/assets/microservices-communication.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/microservices-communication.png
--------------------------------------------------------------------------------
/assets/monolithic-and-microservices-architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/monolithic-and-microservices-architecture.jpg
--------------------------------------------------------------------------------
/assets/node-js-jwt-authentication-mysql-project-structure.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/node-js-jwt-authentication-mysql-project-structure.png
--------------------------------------------------------------------------------
/assets/nodejs-event-loop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/nodejs-event-loop.png
--------------------------------------------------------------------------------
/assets/nodejs_cluster.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/nodejs_cluster.png
--------------------------------------------------------------------------------
/assets/pm2-load-balancer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/pm2-load-balancer.png
--------------------------------------------------------------------------------
/assets/reactor-pattern.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/reactor-pattern.jpg
--------------------------------------------------------------------------------
/assets/star.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/star.png
--------------------------------------------------------------------------------
/assets/temp.txt:
--------------------------------------------------------------------------------
1 | This is test file to test fs module of Node.js
--------------------------------------------------------------------------------
/assets/test.txt:
--------------------------------------------------------------------------------
1 | This is first paragraph!
2 | This is second paragraph!
--------------------------------------------------------------------------------
/assets/testPyramid.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/assets/testPyramid.png
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/.gitignore:
--------------------------------------------------------------------------------
1 | .env
2 | node_modules
3 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/README.md:
--------------------------------------------------------------------------------
1 | # Express and JSON Web Token Authentication Using Asymetric Encryption Algorithm (RSA256)
2 |
3 | When creating jsonwebtoken rather than signing and verifying tokens with a secret key use Asymetric encryption instead using pubic and private key pairs
4 |
5 |
6 |
7 | - `cd` into jwt-authentication folder in your terminal run `mkdir certs`, then type `cd certs`.
8 | - Generate a public and private key for both access and refresh tokens:
9 |
10 | ```bash
11 | /** To generate a public and private key for access tokens */
12 |
13 | // Private Key
14 | >> openssl genrsa -out accessTokenPrivatekey.pem 4096
15 |
16 | // Public Key
17 | >> openssl rsa -pubout -in accessTokenPrivatekey.pem -out accessTokenPublickey.pem
18 | ```
19 |
20 | ```bash
21 | /** To generate a public and private key for refresh tokens */
22 |
23 | // Private Key
24 | >> openssl genrsa -out refreshTokenPrivatekey.pem 4096
25 |
26 | // Public Key
27 | >> openssl rsa -pubout -in refreshTokenPrivatekey.pem -out refreshTokenPublickey.pem
28 | ```
29 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/authServer.js:
--------------------------------------------------------------------------------
1 | require('dotenv').config();
2 |
3 | const express = require('express');
4 | const app = express();
5 | const jwt = require('jsonwebtoken');
6 | const { readFileSync } = require('fs');
7 | const { promisify } = require('util');
8 |
9 | app.use(express.json());
10 |
11 | let refreshTokens = [];
12 |
13 | app.post('/token', async (req, res, next) => {
14 | try {
15 | const refreshToken = req.body.token;
16 | if (refreshToken === null)
17 | res.sendStatus(401).json({ error: 'Provide a token' });
18 | console.log(refreshTokens);
19 | if (!refreshTokens.includes(refreshToken)) return res.sendStatus(403);
20 |
21 | const REFRESH_TOKEN_PUB_KEY = readFileSync(
22 | './certs/refreshTokenPubliKey.pem',
23 | 'utf8'
24 | );
25 |
26 | /** use the refresh Token public key to verify the JWT refresh token that was signed with the private key */
27 | jwt.verify(
28 | refreshToken,
29 | REFRESH_TOKEN_PUB_KEY,
30 | {
31 | algorithms: ['RS256'],
32 | },
33 | (err, user) => {
34 | if (err) res.sendStatus(403).json({ message: err.message });
35 | const accessToken = generateAccessToken(user.name);
36 | res.json({ accessToken: accessToken });
37 | }
38 | );
39 | } catch (error) {
40 | console.log(error.message);
41 | }
42 | });
43 |
44 | app.delete('/logout', (req, res) => {
45 | refreshTokens = refreshTokens.filter((token) => token !== req.body.token);
46 | res.sendStatus(204);
47 | });
48 |
49 | app.post('/login', async (req, res) => {
50 | try {
51 | // Authenticate User
52 | const username = req.body.username;
53 | const user = { name: username };
54 |
55 | const REFRESH_TOKEN_PRIV_KEY = readFileSync(
56 | './certs/refreshTokenPrivateKey.pem',
57 | 'utf8'
58 | );
59 |
60 | const accessToken = generateAccessToken(user);
61 |
62 | /** Use the Refresh Token Private Key to sign a JWT refresh token*/
63 | const refreshToken = jwt.sign({ user }, REFRESH_TOKEN_PRIV_KEY, {
64 | algorithm: 'RS256',
65 | expiresIn: '60s',
66 | });
67 |
68 | refreshTokens.push(refreshToken);
69 | console.log(refreshTokens);
70 | res.json({ accessToken: accessToken, refreshToken: refreshToken });
71 | } catch (err) {
72 | console.log(err.message);
73 | }
74 | });
75 |
76 | function generateAccessToken(user) {
77 | const ACCESS_TOKEN_PRIV_KEY = readFileSync(
78 | './certs/accessTokenPrivateKey.pem',
79 | 'utf8'
80 | );
81 |
82 | /** Use the Access Token Private Key to sign a JWT access token*/
83 | return jwt.sign({ user }, ACCESS_TOKEN_PRIV_KEY, {
84 | algorithm: 'RS256',
85 | expiresIn: '1hr',
86 | });
87 | }
88 |
89 | app.listen(4000, () => console.log(`App is running at http://localhost:4000`));
90 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/certs/accessTokenPrivateKey.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIJKAIBAAKCAgEArt44dqQGQIQpXm3GcQaoyeRL8mIfN3ob8kyNwZfSPSLnDV29
3 | cYfRo6WG7jEnV5ehFwGD5KD0LEP4SlUbs5UjfLstl58B9vVrdlo/Q7oevkcLNion
4 | MjFLURjBtLjDZztCpcpJBIB1cFR45w77k/hEozMKwNutZP5Jm6QtGMFnc3jGlcY/
5 | tar3/AP779SquclE0v6H7mLbxZidHyHICd395Xoe4Q648ERds5bfYWorUpBLmdzr
6 | IUt2M6OV/YITHr/cF8TpDI/6KMjZkboUYm+w/V8uO/Gcz2KUkQqP5jzCjVoRvT0y
7 | /HQ4ZtHnX7P6qZ9ApgyQrrWZIYS1bw6odBJBda+C0kbSuCHnTE+XdIcep/1HKAX7
8 | 5Z9Z9XD6oyjxO82QrBAZ27e3Tk0f/lzIppGHWmihzjVXzQoU1/YDy/K9VPl11ze4
9 | Z/XPwu3P90B9e/bUhIezDHLYiGjGdOELJ4V+f+xtnuP87glFYWQ3btJesnkp4UpW
10 | uJfMvpLwgZnzyiglwGKj+/d7SqeF8D5bhdi/ewRo96lqL4/UzDjg0bGNCy7wNKaP
11 | 6LQfhkeSFWyw4/u73n1Xot9Tvbf5/sQia1tlwhZWKzcWdEXnZb/dBK3bT9XYRcgs
12 | tXwUODkc7cpJ20iIM1rLBpFu7SqQLuEIDVuqnIdcNg52P8GpQ2Bnicq1ZyMCAwEA
13 | AQKCAgEAnHBFRy46QaF6ePXwH9F7UxKgNvk9QB5Hvh5qexTdisAcwEJqZpTBIYvG
14 | CHWE4sHN5Yz/d5velXNBPw6gt6nmk4HIqeogkdTBDKJ0Ep0BP+zCxPQ1GJws6yIg
15 | uRLKDSJg33z2kcZyScnoV515x8jFbtMM/bgJiV5Mb6cSiSEM8arMzdULzfRj4duW
16 | mdpB2e+LWM9IwCVEw6NifSV1lg45RABae7D2FkyzHyUMNlQK6dQZLk8LM0AVQOFK
17 | H/8sJ8gwmDsa2pg7jh0RN2OnNOEDD8kEza+7P3TLwG4Yijs1OcuoLwn/AQbgJmwG
18 | eAHFb9X+ug5nqUTg97GHtxD/9scWMz0iIFYMizpFwi/BuCAKtwnaJbDsQDDGlYct
19 | A0ALw5ZjKlw2+KM09tKn9vUZ08lWoi7VXZwLs8q5YkYMIQbMUZhThyYoyOS/OdrI
20 | Z/KlW9p9/BV6CpoA6tr2k1pn6hGzdRxuG9bjhQzTR1OCOWNizaX11RyOAdkA9kzS
21 | Yx/Q6ynszBZ7CP87SwfAcjSckQM9aa/ZYOKU6qi0wDuMrGm48D6SdQnJLSgqGOin
22 | EQlyofK9f2O65qpU588+uiWUjzI5Nl0/a790pnaGpEWuJYkkGIHhfKQvTdUGjbGq
23 | i1mZZ5POOcjNTu095NW7K67sevfFH0n6jlA6bNuIBkDSz5r8ZVECggEBAOJLDDUr
24 | 7OcxJe8/HBukcoacc0qhZpT60kXzz8zdKLzstiFTl10lIQIg3BggNBjWe/Wa0mlF
25 | 1fm0ML6LaxmAzkOFiSxmy6OR1Q3LjMuzN+fMdeGrUXsngCPNq2wpV5m0MviuYCvt
26 | IZf2Utn37VKmtpkD2T07/4Cr72pG14K2x7Np3HG07tRXSvXEvWmI04St1HOCAWRX
27 | iNjuUBlVrlPdWhlI6FZgwLyby0iVKuCyfaS0ETxkWjXBbLVYW0qjFNxj7GAic2rE
28 | /AP8r04DkjsrAH2vT3VrHUAyPhPe0fPDhBIUbBsrw7NixjSXwhTS/R0i4Q5ndgy2
29 | YssrnGozMOl7xBcCggEBAMXS8qqOzKqraBna20flhUl2Bf50wC6k3e1jgRWBOfo2
30 | Ju0Q1z8ME7UsqMYXUqB3dkmi1+q72jNP5AZxYy9V1Pq2eGP9wR1CiZaeFR/FcXX5
31 | PnZtcuekk1+k4ajPYlF3rTshvYON+mSKRdUN+ocLa61p5cYGGDPs2AGLvNJUAeA+
32 | JdLzDZ3MnjKVC8qaNMmZ1WKqnZkMM3hiok0oylELTFiPhURb8TKzFVdzXA15syfi
33 | h6g/n6cIPhyriRDDP7n6PlYpD0dekbeM9pyGQPZ1X9B9AzAhlbMyQ0FD0MVTpFxw
34 | xG6d7SCEdnKhT1DJcRbSdCOEBJccYbWTm3LDdRHmwNUCggEAFOyzmEcThN06kMDZ
35 | LIUsQd49mu0Ju0TmJKnC0UKx/aY1wSclm+tO/g9jyqdPqexLUg6a3jki7BAJYdUq
36 | dhU+/Wdfo8dtlRZrCPeFcWCFDt4NGGzq/+RLKQRfkYTRINlUzUHyip1GufKA/r66
37 | JyZbRBLjB5KAsbk0TjN2whN8q85iH/GHFANuXwNuMFACnwYj2vpufoTJlqWSqoUN
38 | tZuGNUhUk4gmykntpiyE5noavBwaa+croETedHZTGrexuh9TQCBvY7QLSaMX4rLZ
39 | 1rbHONf5FPZuof0DWHsGFvBBShqxVGHbmr7LbRmLTLmlxgfvn5FZjRtgT0EdGYTa
40 | RPy4yQKCAQBlfo0yJIGtLrQCT98hTAjOX9dDbfML+1pBaUPZHKv6S7488t78Yd3a
41 | nkcZGu4xlhkCPqI4tJiGqv56r8ILjyXuW5/47UAfGvwsYn7EBjDoLjB14kGJx041
42 | TAra6UuwMI6YP/9Td4x3+NlLLhjTIHDmT+araoUQXvuUD3WZE7DCtCAD0t+xjkG8
43 | AexCzks3A84PCSpCU5g0s6ZBoCPs4LcS2M+u+t0M/gR9EZqw7zeTxw2CrOHkeL4l
44 | R3zTNNmFOXayDe7g1ww79/6u39KEoEPAW+M+1nxPrAIFgh2in/87zj954Vy/yjZb
45 | KZfgAvoak28yqZERVmZrGoguoUl3HcThAoIBAEoib+EB2Qjt7UMwIkUGC4/NKOzB
46 | vQE4P5qhTMFQEPn5b3ea048YSIwok9aiEIasj6Mu29yqFoAQ7UaI1aj1UAi9qFzb
47 | amTTYrlcK6AiN7jebodX3y8rXnBwZMs/qdwqoCp/jUk12k6rAML8/e0CautMUMKu
48 | fm2xTBCHp3SzEoWv5FkZsGuWTUqNBclV5wvjYGaYgxFUyt2e0J/2gUTy9O7SdubY
49 | s4nFqfTVjZqHQzHx7FqFUw3qWYl8LsorctMpV2xvqVOfycTDIBsoXa6EwbUUgxta
50 | BBkfLvkkXLUS+Y8GcYkIyztzcigAYUe8/p/w0Py5YHBk7yCq0ZMtJSMxpoc=
51 | -----END RSA PRIVATE KEY-----
52 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/certs/accessTokenPubliKey.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PUBLIC KEY-----
2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEArt44dqQGQIQpXm3GcQao
3 | yeRL8mIfN3ob8kyNwZfSPSLnDV29cYfRo6WG7jEnV5ehFwGD5KD0LEP4SlUbs5Uj
4 | fLstl58B9vVrdlo/Q7oevkcLNionMjFLURjBtLjDZztCpcpJBIB1cFR45w77k/hE
5 | ozMKwNutZP5Jm6QtGMFnc3jGlcY/tar3/AP779SquclE0v6H7mLbxZidHyHICd39
6 | 5Xoe4Q648ERds5bfYWorUpBLmdzrIUt2M6OV/YITHr/cF8TpDI/6KMjZkboUYm+w
7 | /V8uO/Gcz2KUkQqP5jzCjVoRvT0y/HQ4ZtHnX7P6qZ9ApgyQrrWZIYS1bw6odBJB
8 | da+C0kbSuCHnTE+XdIcep/1HKAX75Z9Z9XD6oyjxO82QrBAZ27e3Tk0f/lzIppGH
9 | WmihzjVXzQoU1/YDy/K9VPl11ze4Z/XPwu3P90B9e/bUhIezDHLYiGjGdOELJ4V+
10 | f+xtnuP87glFYWQ3btJesnkp4UpWuJfMvpLwgZnzyiglwGKj+/d7SqeF8D5bhdi/
11 | ewRo96lqL4/UzDjg0bGNCy7wNKaP6LQfhkeSFWyw4/u73n1Xot9Tvbf5/sQia1tl
12 | whZWKzcWdEXnZb/dBK3bT9XYRcgstXwUODkc7cpJ20iIM1rLBpFu7SqQLuEIDVuq
13 | nIdcNg52P8GpQ2Bnicq1ZyMCAwEAAQ==
14 | -----END PUBLIC KEY-----
15 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/certs/refreshTokenPrivateKey.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIJKQIBAAKCAgEAqzeDd8smeUebrYfgDqvawROpzP5Pe/xJo97UHAYj8Fg7K1CI
3 | VC3fNbUxPT6BrRFyb/TOJwRw9lvkfffRUoW/skheEaZf7db+6rgk1OTWsULzPLbo
4 | /AjIPgKRepzWj5STq56ZEbnpdrYmzcWtIlUz9Op/sPdxpUvbioSH0x9gHVU8Poso
5 | lv64h1kehajeC/QN1YUXxKq/IF/p383/RZOULV+7IkWOFsrKxZ5KJ6oNsqvKoa0B
6 | G0zVZ1MX7AbsRCm6FM4ddJMaHFAiSchOFOoB7heqN4Mi/iVJWq084Irc+N64OPB6
7 | 2A9OKWsGmTcm9NtZLa3aicI+7LqS8oMVwUM9ZeOYGbMXVrOHxkPFbI8JM7uz4pg3
8 | sYazyG7nir9bsAXqTDs0l1v0DXhRoAKEV4dJTJE9IHpiJGeIi1ykBbXXV0oW2meE
9 | 9vHMIHiT92C+w33zA7uuZjDk6s9yGWc8LBAdlsD/YfIr5U6A1Ma3weHzcyAcHBtZ
10 | O+1Ao/nZvTsH2EWdZx35Xit2+l6kx0MJs3Db2CIoRoJpvvoEv1ns5jHMYscgXt07
11 | YSwAWKOSSA9aYPQxfa/OBT9qWaDBNK0esJJun03LHf30dT/gJI9MkB0Cn/c/yuaC
12 | w04aDKYVk+AHIXlKLcjTr7M8l3R5J8IlRgT//WAw9Qk8OjGW6tBxs8kY8oECAwEA
13 | AQKCAgEAjx/YxksL3lX9zRHIOntuYfgN+U6dIwfChzm+Fa8MW91lmM+5JqUx8bOF
14 | dazKueHbx7rcmcEcrNQkLSj70f/8Pww/loF9r1QJxCwqncytq4BL1HUSTZ0Jxsxe
15 | 0CBLO7r3tn7ddfPzNUkPJvQXxpty00kzdLtkRMkkvKYM5G9V6S9XLPEm/RHxLzNQ
16 | UGrZMyTQa6zWMZCKNIX4+x04RvEW7NcZl4yNOoBLAOdRFdcRnEn/GSeFxUx1F+pe
17 | FO+0kUZQRxQFi21sZj6WaxcGLnVvJ5igscbteYWxzBsEyK9MCL4lQXPFPNeOfxD4
18 | cxundQfnhEfQZ1f5Qeq07ASoKuYKa8OfvdxSrnQ5F6DgTSeVXukajZM4vJhEOXeV
19 | fKIUI8qfoqb8kSLErZmPjdwvFMeXu8T7JY9LY3LYwZBNDX3fiJXImXQvMiIJtt+d
20 | zhtRb5DypmZq3Kf6bWJga6FGL942hC4p6cvrh7Ri3rI+xcKF1Gu15Y3u8MyMDdEu
21 | eyQZ3SFhibxvN6AExU+RSRdix5HuizJ4ja/LKCaXIWMGdrhQUzJH+dv+vhIQajXI
22 | al29Q+ub3knvCYglm/tqHcN8ZOehWRA0PiJo4fK6lcySBu8cqGcq4EUdA9yHk+EI
23 | Ew6Wylb2ZjGS2lWDNeLZJyHlcobU5VR4ZioU1NKsZ9NcWtk5AAECggEBANhM4SM2
24 | Nd8LkphMv9xwR+ZOc2Bh239mrYlkw7uKW0QpKu5ksEWAK1s/Z/rZgm+2Fmh8w9Lf
25 | FgA9lvW+7AXpU3T2GPibeGza0EhZSTkUWOBa3BtRyJzWGNV4WOnc5wA1Gmx49E+h
26 | zaZ/L+gKxOGRy9PBb9dFKNdGOOCNHHujhjK7H70IjOe+8/pFMaEnHov8TmOSVe3m
27 | fUiaVYTIbrTNkkgKQZAu8iOiXmRv9r3tGzK3XvjPaftbV+Qs502r3IkWzTKXqIwM
28 | 35+HxAZiYV2uweDqpYSYYTxVOugeEWaF+1iT/sWiB0cGuQJ8WUHkqy/V/vOnW4z8
29 | GI2gNF81DKLSmRECggEBAMqkVeOKWVI0+AjRSCzA9zSHkks+u+4tBa62RY8akx4m
30 | TTtSCG/Fc537TkFmtzqoIWO1siNlNi/7wasDdz5foTDcWRMO/1YCPlmz4x8k+4Bs
31 | 1KsMJw92y4++LCU20NrLUMtWd0ClNzVD8oc1/2NRZZJJi6ZgCwg8Y3xOqe6Lyp6N
32 | vaskT/8/7OBhQ3+WLN88tdoVCrWXx72uQ5RbrG21yeeh3u1h2DmlLCldYeMvgfna
33 | Et/nfM1ojr2/QAA5OA4ZUBSPNHEfydVyDo61wUi7O/nUz+yx0VoW1gnMf/noNcOy
34 | 6D8KICjIW5Npnqx0i/i31/NG7ttgb4MPj5Ceh8vdQnECggEBAKvdAjJBO7K69kLv
35 | EK9tw6NaCFC30Hk9M3vsxZ05BOV2tHbxKCJBAbIiAlOOChcLHmjtYYcm3MtaJJ2k
36 | ktLrnvVbKWI33grYHhCuaQDiiu/RIfzPEdCUSO0tD7DaZe2DRDiWLsErNkUp3/3G
37 | uMLmXocltuDcQeQzFrRNSyluOA4NIt3HcnYdAqyD2DhM5feihQKW3pIFxtwuTO8R
38 | du1QPf/hrlCLDLiFpey2Dd7BDBBTJTIbVAF1hbN2fl73xGZk6KxfVnvZKsIOVRIh
39 | j22pksFMkDF4BiKzMfgHFBpbMOgjx5Zu9MtZqx0vgphZwi9jII2nF5ZBJJ07gwF3
40 | HFAvd5ECggEAYWueCxVRGc9zSzHqA/IFJpDiyR/w03F7oOHqEQFSpxT83j7y5WFE
41 | 0zelCJYsEpwP6VLJwHCBG5JqKiAxbKAm60mT3TDBmoTbmt57m1Z5PuWTXGQsRyfy
42 | dzmTGZT/1aAXSJpaHI8ROp9e8pgIHqRcM3b+F09nHl+B6Joc4hz8nTtBawy7FNiT
43 | tc+s1qLJEc2rE5w4GNNOaKdlv+ZOwDO8TIqqlO8MN7Jrx7soO0N0tjycBF7SxiG1
44 | Ng3C5BieFVEgCbJLIPOKYf5Cd2Nz99Zj4BjqmT1ni2sdHXreL7PuXRYex2fDzDd+
45 | pyEI8pnZTQp9XGzGmlsDYTvS5lEAsga+UQKCAQBdEkewEx5ITgvoZwaVoOZ613XA
46 | wmIvHZnOf13TYCFXsQQAZDZdMNeABqWEKU5pKm30OJL1tRUPximgCA9ypYfHf/g3
47 | wwimXzjTOGIQbVG/TBT5SMDYrLOu/5h5N5H/6bj5MWwcGAJIErZuHA8a1g8x/+Fl
48 | 20EZOnEmHVECVGFDDMRGR22ZWB+gwuF3MCBA+I4KxPr1Js0YrrQ8rn3GXe1S7UwV
49 | R6XHN8aMn8qiGctsOluV22wmKVfr3z6gWru0E2bBQ5BalUxIlgKPyn7h+O/v3hE9
50 | X/2ec0UZ4G/dovhYL/US+sYtiRxfgFUh771Z7zAIiSkJeDxwhLePNQ4ges6v
51 | -----END RSA PRIVATE KEY-----
52 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/certs/refreshTokenPubliKey.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN PUBLIC KEY-----
2 | MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAqzeDd8smeUebrYfgDqva
3 | wROpzP5Pe/xJo97UHAYj8Fg7K1CIVC3fNbUxPT6BrRFyb/TOJwRw9lvkfffRUoW/
4 | skheEaZf7db+6rgk1OTWsULzPLbo/AjIPgKRepzWj5STq56ZEbnpdrYmzcWtIlUz
5 | 9Op/sPdxpUvbioSH0x9gHVU8Posolv64h1kehajeC/QN1YUXxKq/IF/p383/RZOU
6 | LV+7IkWOFsrKxZ5KJ6oNsqvKoa0BG0zVZ1MX7AbsRCm6FM4ddJMaHFAiSchOFOoB
7 | 7heqN4Mi/iVJWq084Irc+N64OPB62A9OKWsGmTcm9NtZLa3aicI+7LqS8oMVwUM9
8 | ZeOYGbMXVrOHxkPFbI8JM7uz4pg3sYazyG7nir9bsAXqTDs0l1v0DXhRoAKEV4dJ
9 | TJE9IHpiJGeIi1ykBbXXV0oW2meE9vHMIHiT92C+w33zA7uuZjDk6s9yGWc8LBAd
10 | lsD/YfIr5U6A1Ma3weHzcyAcHBtZO+1Ao/nZvTsH2EWdZx35Xit2+l6kx0MJs3Db
11 | 2CIoRoJpvvoEv1ns5jHMYscgXt07YSwAWKOSSA9aYPQxfa/OBT9qWaDBNK0esJJu
12 | n03LHf30dT/gJI9MkB0Cn/c/yuaCw04aDKYVk+AHIXlKLcjTr7M8l3R5J8IlRgT/
13 | /WAw9Qk8OjGW6tBxs8kY8oECAwEAAQ==
14 | -----END PUBLIC KEY-----
15 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/example.env:
--------------------------------------------------------------------------------
1 | ACCESS_TOKEN_SECRET=some_secret_key
2 |
3 | REFRESH_TOKEN_SECRET=some_secret_key
4 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "current-project",
3 | "version": "1.0.0",
4 | "lockfileVersion": 1,
5 | "requires": true,
6 | "dependencies": {
7 | "abbrev": {
8 | "version": "1.1.1",
9 | "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
10 | "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
11 | "dev": true
12 | },
13 | "accepts": {
14 | "version": "1.3.7",
15 | "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
16 | "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
17 | "requires": {
18 | "mime-types": "~2.1.24",
19 | "negotiator": "0.6.2"
20 | }
21 | },
22 | "anymatch": {
23 | "version": "3.1.2",
24 | "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz",
25 | "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==",
26 | "dev": true,
27 | "requires": {
28 | "normalize-path": "^3.0.0",
29 | "picomatch": "^2.0.4"
30 | }
31 | },
32 | "array-flatten": {
33 | "version": "1.1.1",
34 | "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
35 | "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
36 | },
37 | "balanced-match": {
38 | "version": "1.0.2",
39 | "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
40 | "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
41 | "dev": true
42 | },
43 | "binary-extensions": {
44 | "version": "2.2.0",
45 | "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz",
46 | "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==",
47 | "dev": true
48 | },
49 | "body-parser": {
50 | "version": "1.19.0",
51 | "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
52 | "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==",
53 | "requires": {
54 | "bytes": "3.1.0",
55 | "content-type": "~1.0.4",
56 | "debug": "2.6.9",
57 | "depd": "~1.1.2",
58 | "http-errors": "1.7.2",
59 | "iconv-lite": "0.4.24",
60 | "on-finished": "~2.3.0",
61 | "qs": "6.7.0",
62 | "raw-body": "2.4.0",
63 | "type-is": "~1.6.17"
64 | }
65 | },
66 | "brace-expansion": {
67 | "version": "1.1.11",
68 | "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
69 | "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
70 | "dev": true,
71 | "requires": {
72 | "balanced-match": "^1.0.0",
73 | "concat-map": "0.0.1"
74 | }
75 | },
76 | "braces": {
77 | "version": "3.0.2",
78 | "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
79 | "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
80 | "dev": true,
81 | "requires": {
82 | "fill-range": "^7.0.1"
83 | }
84 | },
85 | "buffer-equal-constant-time": {
86 | "version": "1.0.1",
87 | "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
88 | "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk="
89 | },
90 | "bytes": {
91 | "version": "3.1.0",
92 | "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
93 | "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg=="
94 | },
95 | "chokidar": {
96 | "version": "3.5.3",
97 | "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz",
98 | "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==",
99 | "dev": true,
100 | "requires": {
101 | "anymatch": "~3.1.2",
102 | "braces": "~3.0.2",
103 | "fsevents": "~2.3.2",
104 | "glob-parent": "~5.1.2",
105 | "is-binary-path": "~2.1.0",
106 | "is-glob": "~4.0.1",
107 | "normalize-path": "~3.0.0",
108 | "readdirp": "~3.6.0"
109 | }
110 | },
111 | "concat-map": {
112 | "version": "0.0.1",
113 | "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
114 | "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
115 | "dev": true
116 | },
117 | "content-disposition": {
118 | "version": "0.5.3",
119 | "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz",
120 | "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==",
121 | "requires": {
122 | "safe-buffer": "5.1.2"
123 | }
124 | },
125 | "content-type": {
126 | "version": "1.0.4",
127 | "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
128 | "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA=="
129 | },
130 | "cookie": {
131 | "version": "0.4.0",
132 | "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz",
133 | "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg=="
134 | },
135 | "cookie-signature": {
136 | "version": "1.0.6",
137 | "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
138 | "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
139 | },
140 | "debug": {
141 | "version": "2.6.9",
142 | "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
143 | "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
144 | "requires": {
145 | "ms": "2.0.0"
146 | }
147 | },
148 | "depd": {
149 | "version": "1.1.2",
150 | "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
151 | "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak="
152 | },
153 | "destroy": {
154 | "version": "1.0.4",
155 | "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
156 | "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
157 | },
158 | "dotenv": {
159 | "version": "8.6.0",
160 | "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.6.0.tgz",
161 | "integrity": "sha512-IrPdXQsk2BbzvCBGBOTmmSH5SodmqZNt4ERAZDmW4CT+tL8VtvinqywuANaFu4bOMWki16nqf0e4oC0QIaDr/g=="
162 | },
163 | "ecdsa-sig-formatter": {
164 | "version": "1.0.11",
165 | "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
166 | "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
167 | "requires": {
168 | "safe-buffer": "^5.0.1"
169 | }
170 | },
171 | "ee-first": {
172 | "version": "1.1.1",
173 | "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
174 | "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
175 | },
176 | "encodeurl": {
177 | "version": "1.0.2",
178 | "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
179 | "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k="
180 | },
181 | "escape-html": {
182 | "version": "1.0.3",
183 | "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
184 | "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
185 | },
186 | "etag": {
187 | "version": "1.8.1",
188 | "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
189 | "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc="
190 | },
191 | "express": {
192 | "version": "4.17.1",
193 | "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz",
194 | "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==",
195 | "requires": {
196 | "accepts": "~1.3.7",
197 | "array-flatten": "1.1.1",
198 | "body-parser": "1.19.0",
199 | "content-disposition": "0.5.3",
200 | "content-type": "~1.0.4",
201 | "cookie": "0.4.0",
202 | "cookie-signature": "1.0.6",
203 | "debug": "2.6.9",
204 | "depd": "~1.1.2",
205 | "encodeurl": "~1.0.2",
206 | "escape-html": "~1.0.3",
207 | "etag": "~1.8.1",
208 | "finalhandler": "~1.1.2",
209 | "fresh": "0.5.2",
210 | "merge-descriptors": "1.0.1",
211 | "methods": "~1.1.2",
212 | "on-finished": "~2.3.0",
213 | "parseurl": "~1.3.3",
214 | "path-to-regexp": "0.1.7",
215 | "proxy-addr": "~2.0.5",
216 | "qs": "6.7.0",
217 | "range-parser": "~1.2.1",
218 | "safe-buffer": "5.1.2",
219 | "send": "0.17.1",
220 | "serve-static": "1.14.1",
221 | "setprototypeof": "1.1.1",
222 | "statuses": "~1.5.0",
223 | "type-is": "~1.6.18",
224 | "utils-merge": "1.0.1",
225 | "vary": "~1.1.2"
226 | }
227 | },
228 | "fill-range": {
229 | "version": "7.0.1",
230 | "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
231 | "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
232 | "dev": true,
233 | "requires": {
234 | "to-regex-range": "^5.0.1"
235 | }
236 | },
237 | "finalhandler": {
238 | "version": "1.1.2",
239 | "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz",
240 | "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==",
241 | "requires": {
242 | "debug": "2.6.9",
243 | "encodeurl": "~1.0.2",
244 | "escape-html": "~1.0.3",
245 | "on-finished": "~2.3.0",
246 | "parseurl": "~1.3.3",
247 | "statuses": "~1.5.0",
248 | "unpipe": "~1.0.0"
249 | }
250 | },
251 | "forwarded": {
252 | "version": "0.1.2",
253 | "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz",
254 | "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ="
255 | },
256 | "fresh": {
257 | "version": "0.5.2",
258 | "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
259 | "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
260 | },
261 | "fsevents": {
262 | "version": "2.3.2",
263 | "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
264 | "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
265 | "dev": true,
266 | "optional": true
267 | },
268 | "glob-parent": {
269 | "version": "5.1.2",
270 | "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
271 | "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
272 | "dev": true,
273 | "requires": {
274 | "is-glob": "^4.0.1"
275 | }
276 | },
277 | "has-flag": {
278 | "version": "3.0.0",
279 | "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
280 | "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
281 | "dev": true
282 | },
283 | "http-errors": {
284 | "version": "1.7.2",
285 | "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz",
286 | "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==",
287 | "requires": {
288 | "depd": "~1.1.2",
289 | "inherits": "2.0.3",
290 | "setprototypeof": "1.1.1",
291 | "statuses": ">= 1.5.0 < 2",
292 | "toidentifier": "1.0.0"
293 | }
294 | },
295 | "iconv-lite": {
296 | "version": "0.4.24",
297 | "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
298 | "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
299 | "requires": {
300 | "safer-buffer": ">= 2.1.2 < 3"
301 | }
302 | },
303 | "ignore-by-default": {
304 | "version": "1.0.1",
305 | "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz",
306 | "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==",
307 | "dev": true
308 | },
309 | "inherits": {
310 | "version": "2.0.3",
311 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
312 | "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
313 | },
314 | "ipaddr.js": {
315 | "version": "1.9.1",
316 | "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
317 | "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
318 | },
319 | "is-binary-path": {
320 | "version": "2.1.0",
321 | "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
322 | "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
323 | "dev": true,
324 | "requires": {
325 | "binary-extensions": "^2.0.0"
326 | }
327 | },
328 | "is-extglob": {
329 | "version": "2.1.1",
330 | "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
331 | "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
332 | "dev": true
333 | },
334 | "is-glob": {
335 | "version": "4.0.3",
336 | "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
337 | "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
338 | "dev": true,
339 | "requires": {
340 | "is-extglob": "^2.1.1"
341 | }
342 | },
343 | "is-number": {
344 | "version": "7.0.0",
345 | "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
346 | "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
347 | "dev": true
348 | },
349 | "jsonwebtoken": {
350 | "version": "8.5.1",
351 | "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz",
352 | "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==",
353 | "requires": {
354 | "jws": "^3.2.2",
355 | "lodash.includes": "^4.3.0",
356 | "lodash.isboolean": "^3.0.3",
357 | "lodash.isinteger": "^4.0.4",
358 | "lodash.isnumber": "^3.0.3",
359 | "lodash.isplainobject": "^4.0.6",
360 | "lodash.isstring": "^4.0.1",
361 | "lodash.once": "^4.0.0",
362 | "ms": "^2.1.1",
363 | "semver": "^5.6.0"
364 | },
365 | "dependencies": {
366 | "ms": {
367 | "version": "2.1.2",
368 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
369 | "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
370 | }
371 | }
372 | },
373 | "jwa": {
374 | "version": "1.4.1",
375 | "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
376 | "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
377 | "requires": {
378 | "buffer-equal-constant-time": "1.0.1",
379 | "ecdsa-sig-formatter": "1.0.11",
380 | "safe-buffer": "^5.0.1"
381 | }
382 | },
383 | "jws": {
384 | "version": "3.2.2",
385 | "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
386 | "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
387 | "requires": {
388 | "jwa": "^1.4.1",
389 | "safe-buffer": "^5.0.1"
390 | }
391 | },
392 | "lodash.includes": {
393 | "version": "4.3.0",
394 | "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
395 | "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8="
396 | },
397 | "lodash.isboolean": {
398 | "version": "3.0.3",
399 | "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
400 | "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY="
401 | },
402 | "lodash.isinteger": {
403 | "version": "4.0.4",
404 | "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
405 | "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M="
406 | },
407 | "lodash.isnumber": {
408 | "version": "3.0.3",
409 | "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
410 | "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w="
411 | },
412 | "lodash.isplainobject": {
413 | "version": "4.0.6",
414 | "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
415 | "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs="
416 | },
417 | "lodash.isstring": {
418 | "version": "4.0.1",
419 | "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
420 | "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE="
421 | },
422 | "lodash.once": {
423 | "version": "4.1.1",
424 | "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
425 | "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w="
426 | },
427 | "media-typer": {
428 | "version": "0.3.0",
429 | "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
430 | "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g="
431 | },
432 | "merge-descriptors": {
433 | "version": "1.0.1",
434 | "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
435 | "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E="
436 | },
437 | "methods": {
438 | "version": "1.1.2",
439 | "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
440 | "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4="
441 | },
442 | "mime": {
443 | "version": "1.6.0",
444 | "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
445 | "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="
446 | },
447 | "mime-db": {
448 | "version": "1.44.0",
449 | "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.44.0.tgz",
450 | "integrity": "sha512-/NOTfLrsPBVeH7YtFPgsVWveuL+4SjjYxaQ1xtM1KMFj7HdxlBlxeyNLzhyJVx7r4rZGJAZ/6lkKCitSc/Nmpg=="
451 | },
452 | "mime-types": {
453 | "version": "2.1.27",
454 | "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.27.tgz",
455 | "integrity": "sha512-JIhqnCasI9yD+SsmkquHBxTSEuZdQX5BuQnS2Vc7puQQQ+8yiP5AY5uWhpdv4YL4VM5c6iliiYWPgJ/nJQLp7w==",
456 | "requires": {
457 | "mime-db": "1.44.0"
458 | }
459 | },
460 | "minimatch": {
461 | "version": "3.1.2",
462 | "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
463 | "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
464 | "dev": true,
465 | "requires": {
466 | "brace-expansion": "^1.1.7"
467 | }
468 | },
469 | "ms": {
470 | "version": "2.0.0",
471 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
472 | "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
473 | },
474 | "negotiator": {
475 | "version": "0.6.2",
476 | "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
477 | "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
478 | },
479 | "nodemon": {
480 | "version": "2.0.20",
481 | "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.20.tgz",
482 | "integrity": "sha512-Km2mWHKKY5GzRg6i1j5OxOHQtuvVsgskLfigG25yTtbyfRGn/GNvIbRyOf1PSCKJ2aT/58TiuUsuOU5UToVViw==",
483 | "dev": true,
484 | "requires": {
485 | "chokidar": "^3.5.2",
486 | "debug": "^3.2.7",
487 | "ignore-by-default": "^1.0.1",
488 | "minimatch": "^3.1.2",
489 | "pstree.remy": "^1.1.8",
490 | "semver": "^5.7.1",
491 | "simple-update-notifier": "^1.0.7",
492 | "supports-color": "^5.5.0",
493 | "touch": "^3.1.0",
494 | "undefsafe": "^2.0.5"
495 | },
496 | "dependencies": {
497 | "debug": {
498 | "version": "3.2.7",
499 | "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
500 | "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
501 | "dev": true,
502 | "requires": {
503 | "ms": "^2.1.1"
504 | }
505 | },
506 | "ms": {
507 | "version": "2.1.3",
508 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
509 | "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
510 | "dev": true
511 | }
512 | }
513 | },
514 | "nopt": {
515 | "version": "1.0.10",
516 | "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz",
517 | "integrity": "sha512-NWmpvLSqUrgrAC9HCuxEvb+PSloHpqVu+FqcO4eeF2h5qYRhA7ev6KvelyQAKtegUbC6RypJnlEOhd8vloNKYg==",
518 | "dev": true,
519 | "requires": {
520 | "abbrev": "1"
521 | }
522 | },
523 | "normalize-path": {
524 | "version": "3.0.0",
525 | "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
526 | "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
527 | "dev": true
528 | },
529 | "on-finished": {
530 | "version": "2.3.0",
531 | "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
532 | "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
533 | "requires": {
534 | "ee-first": "1.1.1"
535 | }
536 | },
537 | "parseurl": {
538 | "version": "1.3.3",
539 | "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
540 | "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
541 | },
542 | "path-to-regexp": {
543 | "version": "0.1.7",
544 | "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
545 | "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
546 | },
547 | "picomatch": {
548 | "version": "2.3.1",
549 | "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
550 | "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
551 | "dev": true
552 | },
553 | "proxy-addr": {
554 | "version": "2.0.6",
555 | "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.6.tgz",
556 | "integrity": "sha512-dh/frvCBVmSsDYzw6n926jv974gddhkFPfiN8hPOi30Wax25QZyZEGveluCgliBnqmuM+UJmBErbAUFIoDbjOw==",
557 | "requires": {
558 | "forwarded": "~0.1.2",
559 | "ipaddr.js": "1.9.1"
560 | }
561 | },
562 | "pstree.remy": {
563 | "version": "1.1.8",
564 | "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
565 | "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==",
566 | "dev": true
567 | },
568 | "qs": {
569 | "version": "6.7.0",
570 | "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz",
571 | "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ=="
572 | },
573 | "range-parser": {
574 | "version": "1.2.1",
575 | "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
576 | "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="
577 | },
578 | "raw-body": {
579 | "version": "2.4.0",
580 | "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz",
581 | "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==",
582 | "requires": {
583 | "bytes": "3.1.0",
584 | "http-errors": "1.7.2",
585 | "iconv-lite": "0.4.24",
586 | "unpipe": "1.0.0"
587 | }
588 | },
589 | "readdirp": {
590 | "version": "3.6.0",
591 | "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
592 | "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
593 | "dev": true,
594 | "requires": {
595 | "picomatch": "^2.2.1"
596 | }
597 | },
598 | "safe-buffer": {
599 | "version": "5.1.2",
600 | "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
601 | "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
602 | },
603 | "safer-buffer": {
604 | "version": "2.1.2",
605 | "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
606 | "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
607 | },
608 | "semver": {
609 | "version": "5.7.1",
610 | "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
611 | "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ=="
612 | },
613 | "send": {
614 | "version": "0.17.1",
615 | "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz",
616 | "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==",
617 | "requires": {
618 | "debug": "2.6.9",
619 | "depd": "~1.1.2",
620 | "destroy": "~1.0.4",
621 | "encodeurl": "~1.0.2",
622 | "escape-html": "~1.0.3",
623 | "etag": "~1.8.1",
624 | "fresh": "0.5.2",
625 | "http-errors": "~1.7.2",
626 | "mime": "1.6.0",
627 | "ms": "2.1.1",
628 | "on-finished": "~2.3.0",
629 | "range-parser": "~1.2.1",
630 | "statuses": "~1.5.0"
631 | },
632 | "dependencies": {
633 | "ms": {
634 | "version": "2.1.1",
635 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
636 | "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg=="
637 | }
638 | }
639 | },
640 | "serve-static": {
641 | "version": "1.14.1",
642 | "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz",
643 | "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==",
644 | "requires": {
645 | "encodeurl": "~1.0.2",
646 | "escape-html": "~1.0.3",
647 | "parseurl": "~1.3.3",
648 | "send": "0.17.1"
649 | }
650 | },
651 | "setprototypeof": {
652 | "version": "1.1.1",
653 | "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
654 | "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
655 | },
656 | "simple-update-notifier": {
657 | "version": "1.0.7",
658 | "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-1.0.7.tgz",
659 | "integrity": "sha512-BBKgR84BJQJm6WjWFMHgLVuo61FBDSj1z/xSFUIozqO6wO7ii0JxCqlIud7Enr/+LhlbNI0whErq96P2qHNWew==",
660 | "dev": true,
661 | "requires": {
662 | "semver": "~7.0.0"
663 | },
664 | "dependencies": {
665 | "semver": {
666 | "version": "7.0.0",
667 | "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz",
668 | "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==",
669 | "dev": true
670 | }
671 | }
672 | },
673 | "statuses": {
674 | "version": "1.5.0",
675 | "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
676 | "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
677 | },
678 | "supports-color": {
679 | "version": "5.5.0",
680 | "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
681 | "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
682 | "dev": true,
683 | "requires": {
684 | "has-flag": "^3.0.0"
685 | }
686 | },
687 | "to-regex-range": {
688 | "version": "5.0.1",
689 | "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
690 | "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
691 | "dev": true,
692 | "requires": {
693 | "is-number": "^7.0.0"
694 | }
695 | },
696 | "toidentifier": {
697 | "version": "1.0.0",
698 | "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
699 | "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw=="
700 | },
701 | "touch": {
702 | "version": "3.1.0",
703 | "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz",
704 | "integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==",
705 | "dev": true,
706 | "requires": {
707 | "nopt": "~1.0.10"
708 | }
709 | },
710 | "type-is": {
711 | "version": "1.6.18",
712 | "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
713 | "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
714 | "requires": {
715 | "media-typer": "0.3.0",
716 | "mime-types": "~2.1.24"
717 | }
718 | },
719 | "undefsafe": {
720 | "version": "2.0.5",
721 | "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",
722 | "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==",
723 | "dev": true
724 | },
725 | "unpipe": {
726 | "version": "1.0.0",
727 | "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
728 | "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw="
729 | },
730 | "utils-merge": {
731 | "version": "1.0.1",
732 | "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
733 | "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM="
734 | },
735 | "vary": {
736 | "version": "1.1.2",
737 | "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
738 | "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
739 | }
740 | }
741 | }
742 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "current-project",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "devStart": "nodemon server.js",
8 | "devStartAuth": "nodemon authServer.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "dotenv": "^8.6.0",
16 | "express": "^4.17.1",
17 | "jsonwebtoken": "^8.5.1"
18 | },
19 | "devDependencies": {
20 | "nodemon": "^2.0.20"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/requests.rest:
--------------------------------------------------------------------------------
1 | GET http://localhost:3000/posts
2 | Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7Im5hbWUiOiJhZG1pbiJ9LCJpYXQiOjE2NDI4NTA2NzUsImV4cCI6MTY0Mjg1NDI3NX0.ATn_q-pOlEfpsADdMslPIuRC1RK0i7eqEE9u_Ce9xv0iMyHBoYveMa-iS-IDfymrtfY1o5nhpil-8zoAtluRlVV3KdI4W5VOp0BnY16y3R-UaRW-pd8r6oLHvcCHKYXso3IgIIfan31BiFULIKit7btDoSJN-fqj2xk8LlAVDgBBSlqLGf1XbU8s0RvlhHWPxwZFKrJSfN3j5fud4jLUgpJoPAdwR0PxN9GYcISFRDzK0s_aFchvgdQWJ8QH0pbQGp759cVffB8eTgdFguse75QcIqsN53wllYa7m1S3oxmQgkCVy1GPkeaezUgEQ9w6xVILSiWVdEIHbOumG2nGS6WDGeJbsYuPHYe4ocR7jQiDbv3-0v9jiwGAuxuYqosTnc5pVBiW6U3U81MrG6v8ENcHYhz98LgMOFGBB4xckd1VP57vnAzQwV-lm2iiTHFYqt28G3-XZMtGQzAl_PCszCSekbS80nNjghD_7fsStEb5HBjRJiaqo-E6UIApdI1fxoSQkpjtsnE4EFzDCvETz2Up30uUVFr31DJFo8VsP046ZrlJz2Powgsa8Kj93lNk8sG2lEcge0FKrRG7SAsQ_857h1nCtNql6fdYm_yn1V6xBakZFeAchROih1mZixEpK4AzAKdIomc-4gn7vGCaHSzJlq8auLE2RK8XSm39uNA
3 |
4 | ###
5 |
6 | DELETE http://localhost:4000/logout
7 | Content-Type: application/json
8 |
9 | {
10 | "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmltIiwiaWF0IjoxNTY4NzU5OTIyfQ.RT6wszuCeFLwC_6ksmNMIELxiC5s-uRivfRxyZof5ag"
11 | }
12 |
13 | ###
14 |
15 | POST http://localhost:4000/token
16 | Content-Type: application/json
17 |
18 | {
19 | "token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7Im5hbWUiOiJhZG1pbiJ9LCJpYXQiOjE2NDI3OTY4MjksImV4cCI6MTY0Mjc5Njg4OX0.NaLCkDOGVT9vUzO7m367OmY85cG2LsSFnCzz05XGowPXqCLgxv1POwydN8M2ZoTJcSoW5OsGt7LBRaGbvuWfatKNjH6O8ToP-pnVI5USzs4cAapd9JaDpa57X5fCAmnk7FwBOVIs7tZzVcYle0w2MPOJNrODCkg6n8m3JKefYLDk9CLgE_gnI38dTPateA4lN6GliD3DiQm7oRe8KALbQD3710qe0cpW126Mim_7Sl2B2ltdpmWxvRa87V--LEtuejrhGiv1U9Vk-HbMlqv5mou_e7d2NVU3i1sJkAdJ6TTTzDShWSndzhRc2-e0usfKBID7yeEP5LzwGvDuQCYQfnmpzWMfPAyEBaobAoDv7Pzhsmo66L0P-86LBgYD8P0dO4Bjq-r2jgPC-Y2sV9rmj-g7AC9GfPgdxJmXu6s8gdu-dsamBtFZdstFsErSZ8221iW9KB_EZ8ya1WFXoDzgDWJo5cad5rjxADygPE4qUB6fQQucey4R07gksiK05kze4FLNFUKjRDXFxTmGgqnJvo2QgMzA3OcKWB8WJq6SvQmtMQMy7l3xRn6fyj_qMFIYpmP4vAIGW34YgWLh8XiW2ijnQNCoU31XE0OV_atPJRYHnNKh5BaFVrbFq2yorn3hSuOnBlFukitlJclLdNTgoQ3MqQDxivp9Jm8pERpnT5U"
20 | }
21 |
22 | ###
23 |
24 | POST http://localhost:4000/login
25 | Content-Type: application/json
26 |
27 | {
28 | "username": "admin"
29 | }
30 |
--------------------------------------------------------------------------------
/jwt-asymmetric-cryptography-authentication/server.js:
--------------------------------------------------------------------------------
1 | require('dotenv').config();
2 |
3 | const express = require('express');
4 | const app = express();
5 | const jwt = require('jsonwebtoken');
6 | const { readFileSync } = require('fs');
7 |
8 | app.use(express.json());
9 |
10 | const posts = [
11 | {
12 | username: 'admin',
13 | title: 'Post 1',
14 | },
15 | {
16 | username: 'root',
17 | title: 'Post 2',
18 | },
19 | ];
20 |
21 | app.get('/posts', authenticateToken, (req, res) => {
22 | const { name } = req.user;
23 | console.log(req.user.name);
24 | res.json(posts.filter((post) => post.username === req.user.name));
25 | });
26 |
27 | function authenticateToken(req, res, next) {
28 | let token;
29 | if (
30 | req.headers.authorization &&
31 | req.headers.authorization.startsWith('Bearer')
32 | )
33 | token = req.headers.authorization.split(' ')[1];
34 | if (!token) res.status(401).json({ message: 'Opps! you need to login' });
35 |
36 | const ACCESS_TOKEN_PUB_KEY = readFileSync(
37 | './certs/accessTokenPubliKey.pem',
38 | 'utf-8'
39 | );
40 |
41 | /** Use the Access token Public Key to verify the JWT access token */
42 | jwt.verify(
43 | token,
44 | ACCESS_TOKEN_PUB_KEY,
45 | {
46 | algorithms: ['RS256'],
47 | },
48 | (err, user) => {
49 | console.log(err);
50 | if (err) res.status(403);
51 | console.log(user);
52 | req.user = user.user;
53 | next();
54 | }
55 | );
56 | }
57 |
58 | app.listen(3000, () => console.log(`App is running`));
59 |
--------------------------------------------------------------------------------
/jwt-authentication/.gitignore:
--------------------------------------------------------------------------------
1 | .env
2 | node_modules
3 |
--------------------------------------------------------------------------------
/jwt-authentication/README.md:
--------------------------------------------------------------------------------
1 | # Express and JSON Web Token Authentication
2 |
3 |
4 | ## Generate Random Access Token
5 |
6 | ```bash
7 | node > require('crypto').randomBytes(64).toString('hex');
8 |
9 | // Output
10 |
11 | 'e366bb13beebb0b9c8611dca7dc13d4badf7f303c374151cab5dfbb21196dede06224b3a210fdbd6f9392ac906b0f0662ff3480ea62c6374078928af177db161'
12 | ```
13 |
14 | ## Reference
15 |
16 | * *[https://github.com/auth0/node-jsonwebtoken#readme](https://github.com/auth0/node-jsonwebtoken#readme)*
--------------------------------------------------------------------------------
/jwt-authentication/authServer.js:
--------------------------------------------------------------------------------
1 | require('dotenv').config()
2 |
3 | const express = require('express')
4 | const app = express()
5 | const jwt = require('jsonwebtoken')
6 |
7 | app.use(express.json())
8 |
9 | let refreshTokens = []
10 |
11 | app.post('/token', (req, res) => {
12 | const refreshToken = req.body.token
13 | if (refreshToken == null) return res.sendStatus(401)
14 | if (!refreshTokens.includes(refreshToken)) return res.sendStatus(403)
15 | jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
16 | if (err) return res.sendStatus(403)
17 | const accessToken = generateAccessToken({ name: user.name })
18 | res.json({ accessToken: accessToken })
19 | })
20 | })
21 |
22 | app.delete('/logout', (req, res) => {
23 | refreshTokens = refreshTokens.filter(token => token !== req.body.token)
24 | res.sendStatus(204)
25 | })
26 |
27 | app.post('/login', (req, res) => {
28 | // Authenticate User
29 |
30 | const username = req.body.username
31 | const user = { name: username }
32 |
33 | const accessToken = generateAccessToken(user)
34 | const refreshToken = jwt.sign(user, process.env.REFRESH_TOKEN_SECRET)
35 | refreshTokens.push(refreshToken)
36 | res.json({ accessToken: accessToken, refreshToken: refreshToken })
37 | })
38 |
39 | function generateAccessToken(user) {
40 | return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '15s' })
41 | }
42 |
43 | app.listen(4000)
--------------------------------------------------------------------------------
/jwt-authentication/example.env:
--------------------------------------------------------------------------------
1 | ACCESS_TOKEN_SECRET=some_secret_key
2 |
3 | REFRESH_TOKEN_SECRET=some_secret_key
4 |
--------------------------------------------------------------------------------
/jwt-authentication/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "current-project",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "devStart": "nodemon server.js",
8 | "devStartAuth": "nodemon authServer.js",
9 | "test": "echo \"Error: no test specified\" && exit 1"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "dotenv": "^8.1.0",
16 | "express": "^4.17.1",
17 | "jsonwebtoken": "^8.5.1"
18 | },
19 | "devDependencies": {
20 | "nodemon": "^1.19.2"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/jwt-authentication/requests.rest:
--------------------------------------------------------------------------------
1 | GET http://localhost:3000/posts
2 | Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmltIiwiaWF0IjoxNTY4NzU5ODEyLCJleHAiOjE1Njg3NTk4Mjd9.0i6Im2gKz7jj8wM7aZZzOPaBS_xHoZWAqBwnldn-lQQ
3 |
4 | ###
5 |
6 | DELETE http://localhost:4000/logout
7 | Content-Type: application/json
8 |
9 | {
10 | "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmltIiwiaWF0IjoxNTY4NzU5OTIyfQ.RT6wszuCeFLwC_6ksmNMIELxiC5s-uRivfRxyZof5ag"
11 | }
12 |
13 | ###
14 |
15 | POST http://localhost:4000/token
16 | Content-Type: application/json
17 |
18 | {
19 | "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmltIiwiaWF0IjoxNTY4NzU5OTIyfQ.RT6wszuCeFLwC_6ksmNMIELxiC5s-uRivfRxyZof5ag"
20 | }
21 |
22 | ###
23 |
24 | POST http://localhost:4000/login
25 | Content-Type: application/json
26 |
27 | {
28 | "username": "admin"
29 | }
30 |
--------------------------------------------------------------------------------
/jwt-authentication/server.js:
--------------------------------------------------------------------------------
1 | require('dotenv').config()
2 |
3 | const express = require('express')
4 | const app = express()
5 | const jwt = require('jsonwebtoken')
6 |
7 | app.use(express.json())
8 |
9 | const posts = [
10 | {
11 | username: 'admin',
12 | title: 'Post 1'
13 | },
14 | {
15 | username: 'root',
16 | title: 'Post 2'
17 | }
18 | ]
19 |
20 | app.get('/posts', authenticateToken, (req, res) => {
21 | res.json(posts.filter(post => post.username === req.user.name))
22 | })
23 |
24 | function authenticateToken(req, res, next) {
25 | const authHeader = req.headers['authorization']
26 | const token = authHeader && authHeader.split(' ')[1]
27 | if (token == null) return res.sendStatus(401)
28 |
29 | jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
30 | console.log(err)
31 | if (err) return res.sendStatus(403)
32 | req.user = user
33 | next()
34 | })
35 | }
36 |
37 | app.listen(3000);
38 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | package-lock.json
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/README.md:
--------------------------------------------------------------------------------
1 | ## Node.js Token Based Authentication & Authorization
2 |
3 |
4 | #### Project Setup
5 | ```
6 | npm install
7 | ```
8 |
9 | #### Run
10 | ```
11 | npm start
12 | ```
13 |
14 | ## Rest APIs
15 |
16 | | Methods | Urls | Actions |
17 | |---------|------------------|-------------------------|
18 | | POST | /api/auth/singup |Singup new account |
19 | | POST | /api/auth/singin | Login an account |
20 | | GET | /api/test/all | Retrieve public content |
21 | | GET | /api/test/user | Access User Content |
22 | | GET | /api/test/mod | Access Moderator Content|
23 | | GET | /api/test/admin | Access Admin Content |
24 |
25 |
26 | ## Technology
27 |
28 | * Express.js
29 | * bcryptjs
30 | * jsonwebtoken
31 | * Sequelize
32 | * MySQL
33 | * Nodemon
34 | * RestClient
35 |
36 | ## Project Structure
37 |
38 |
39 |
40 | ## Reference
41 |
42 | * *[Authentication & Authorization in Node](https://bezkoder.com/node-js-jwt-authentication-mysql/)*
43 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/config/auth.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | secret: "bezkoder-secret-key"
3 | };
4 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/config/db.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | HOST: "localhost",
3 | USER: "root",
4 | PASSWORD: "root",
5 | DB: "testdb",
6 | dialect: "mysql",
7 | pool: {
8 | max: 5,
9 | min: 0,
10 | acquire: 30000,
11 | idle: 10000
12 | }
13 | };
14 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/config/testdb.sql:
--------------------------------------------------------------------------------
1 | -- MySQL dump 10.10
2 | --
3 | -- Host: localhost Database: testdb
4 | -- ------------------------------------------------------
5 | -- Server version 5.0.13-rc-nt
6 |
7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
10 | /*!40101 SET NAMES utf8 */;
11 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
12 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
13 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
14 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
15 |
16 | --
17 | -- Table structure for table `roles`
18 | --
19 |
20 | DROP TABLE IF EXISTS `roles`;
21 | CREATE TABLE `roles` (
22 | `id` int(11) NOT NULL default '0',
23 | `name` varchar(255) default NULL,
24 | `createdAt` datetime NOT NULL,
25 | `updatedAt` datetime NOT NULL,
26 | PRIMARY KEY (`id`)
27 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
28 |
29 | --
30 | -- Dumping data for table `roles`
31 | --
32 |
33 |
34 | /*!40000 ALTER TABLE `roles` DISABLE KEYS */;
35 | LOCK TABLES `roles` WRITE;
36 | INSERT INTO `roles` VALUES (1,'user','2020-07-01 09:05:39','2020-07-01 09:05:39'),(2,'moderator','2020-07-01 09:05:39','2020-07-01 09:05:39'),(3,'admin','2020-07-01 09:05:39','2020-07-01 09:05:39');
37 | UNLOCK TABLES;
38 | /*!40000 ALTER TABLE `roles` ENABLE KEYS */;
39 |
40 | --
41 | -- Table structure for table `user_roles`
42 | --
43 |
44 | DROP TABLE IF EXISTS `user_roles`;
45 | CREATE TABLE `user_roles` (
46 | `createdAt` datetime NOT NULL,
47 | `updatedAt` datetime NOT NULL,
48 | `roleId` int(11) NOT NULL default '0',
49 | `userId` int(11) NOT NULL default '0',
50 | PRIMARY KEY (`roleId`,`userId`),
51 | KEY `userId` (`userId`),
52 | CONSTRAINT `user_roles_ibfk_1` FOREIGN KEY (`roleId`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
53 | CONSTRAINT `user_roles_ibfk_2` FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
54 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
55 |
56 | --
57 | -- Dumping data for table `user_roles`
58 | --
59 |
60 |
61 | /*!40000 ALTER TABLE `user_roles` DISABLE KEYS */;
62 | LOCK TABLES `user_roles` WRITE;
63 | INSERT INTO `user_roles` VALUES ('2020-07-01 09:05:39','2020-07-01 09:05:39',1,2),('2020-07-01 09:05:39','2020-07-01 09:05:39',1,3),('2020-07-01 09:51:43','2020-07-01 09:51:43',1,4),('2020-07-01 09:05:39','2020-07-01 09:05:39',2,2),('2020-07-01 09:51:43','2020-07-01 09:51:43',2,4);
64 | UNLOCK TABLES;
65 | /*!40000 ALTER TABLE `user_roles` ENABLE KEYS */;
66 |
67 | --
68 | -- Table structure for table `users`
69 | --
70 |
71 | DROP TABLE IF EXISTS `users`;
72 | CREATE TABLE `users` (
73 | `id` int(11) NOT NULL auto_increment,
74 | `username` varchar(255) default NULL,
75 | `email` varchar(255) default NULL,
76 | `password` varchar(255) default NULL,
77 | `createdAt` datetime NOT NULL,
78 | `updatedAt` datetime NOT NULL,
79 | PRIMARY KEY (`id`)
80 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
81 |
82 | --
83 | -- Dumping data for table `users`
84 | --
85 |
86 |
87 | /*!40000 ALTER TABLE `users` DISABLE KEYS */;
88 | LOCK TABLES `users` WRITE;
89 | INSERT INTO `users` VALUES (1,'admin','admin@gmail.com','$2a$08$w3cYCF.N0UQZO19z8CQSZ.whzxFS5vMoi9k51g3TQx9r5tkwrIXO2','2020-07-01 09:05:39','2020-07-01 09:05:39'),(2,'mod','mod@gmail.com','$2a$08$tTj1l28esAxPSSvl3YqKl./nz35vQF7Y76jGtzcYUhHtGy6d.1/ze','2020-07-01 09:05:39','2020-07-01 09:05:39'),(3,'user','user@gmail.com','$2a$08$U2F07dLyYZjzTxQbFMCAcOd1k8V1o9f6E4TGVJHpy0V6/DC7iS0CS','2020-07-01 09:05:39','2020-07-01 09:05:39'),(4,'alex','alex@gmail.com','$2a$08$kxyBECtuoxqFdEuxDYagyOK0fyHx9FUFtAFjB.bFTC98ifTTY1qQm','2020-07-01 09:51:43','2020-07-01 09:51:43');
90 | UNLOCK TABLES;
91 | /*!40000 ALTER TABLE `users` ENABLE KEYS */;
92 |
93 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
94 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
95 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
96 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
97 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
98 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
99 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
100 |
101 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/controllers/auth.controller.js:
--------------------------------------------------------------------------------
1 | const db = require("../models");
2 | const config = require("../config/auth.config");
3 | const User = db.user;
4 | const Role = db.role;
5 |
6 | const Op = db.Sequelize.Op;
7 |
8 | var jwt = require("jsonwebtoken");
9 | var bcrypt = require("bcryptjs");
10 |
11 | exports.signup = (req, res) => {
12 | // Save User to Database
13 | User.create({
14 | username: req.body.username,
15 | email: req.body.email,
16 | password: bcrypt.hashSync(req.body.password, 8)
17 | })
18 | .then(user => {
19 | if (req.body.roles) {
20 | Role.findAll({
21 | where: {
22 | name: {
23 | [Op.or]: req.body.roles
24 | }
25 | }
26 | }).then(roles => {
27 | user.setRoles(roles).then(() => {
28 | res.send({ message: "User registered successfully!" });
29 | });
30 | });
31 | } else {
32 | // user role = 1
33 | user.setRoles([1]).then(() => {
34 | res.send({ message: "User registered successfully!" });
35 | });
36 | }
37 | })
38 | .catch(err => {
39 | res.status(500).send({ message: err.message });
40 | });
41 | };
42 |
43 | exports.signin = (req, res) => {
44 | User.findOne({
45 | where: {
46 | username: req.body.username
47 | }
48 | })
49 | .then(user => {
50 | if (!user) {
51 | return res.status(404).send({ message: "User Not found." });
52 | }
53 |
54 | var passwordIsValid = bcrypt.compareSync(
55 | req.body.password,
56 | user.password
57 | );
58 |
59 | if (!passwordIsValid) {
60 | return res.status(401).send({
61 | accessToken: null,
62 | message: "Invalid Password!"
63 | });
64 | }
65 |
66 | var token = jwt.sign({ id: user.id }, config.secret, {
67 | expiresIn: 86400 // 24 hours
68 | });
69 |
70 | var authorities = [];
71 | user.getRoles().then(roles => {
72 | for (let i = 0; i < roles.length; i++) {
73 | authorities.push("ROLE_" + roles[i].name.toUpperCase());
74 | }
75 | res.status(200).send({
76 | id: user.id,
77 | username: user.username,
78 | email: user.email,
79 | roles: authorities,
80 | accessToken: token
81 | });
82 | });
83 | })
84 | .catch(err => {
85 | res.status(500).send({ message: err.message });
86 | });
87 | };
88 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/controllers/user.controller.js:
--------------------------------------------------------------------------------
1 | exports.allAccess = (req, res) => {
2 | res.status(200).send("Public Content.");
3 | };
4 |
5 | exports.userBoard = (req, res) => {
6 | res.status(200).send("User Content.");
7 | };
8 |
9 | exports.adminBoard = (req, res) => {
10 | res.status(200).send("Admin Content.");
11 | };
12 |
13 | exports.moderatorBoard = (req, res) => {
14 | res.status(200).send("Moderator Content.");
15 | };
16 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/middleware/authJwt.js:
--------------------------------------------------------------------------------
1 | const jwt = require("jsonwebtoken");
2 | const config = require("../config/auth.config.js");
3 | const db = require("../models");
4 | const User = db.user;
5 |
6 | verifyToken = (req, res, next) => {
7 | let token = req.headers["x-access-token"];
8 |
9 | if (!token) {
10 | return res.status(403).send({
11 | message: "No token provided!"
12 | });
13 | }
14 |
15 | jwt.verify(token, config.secret, (err, decoded) => {
16 | if (err) {
17 | return res.status(401).send({
18 | message: "Unauthorized!"
19 | });
20 | }
21 | req.userId = decoded.id;
22 | next();
23 | });
24 | };
25 |
26 | isAdmin = (req, res, next) => {
27 | User.findByPk(req.userId).then(user => {
28 | user.getRoles().then(roles => {
29 | for (let i = 0; i < roles.length; i++) {
30 | if (roles[i].name === "admin") {
31 | next();
32 | return;
33 | }
34 | }
35 |
36 | res.status(403).send({
37 | message: "Require Admin Role!"
38 | });
39 | return;
40 | });
41 | });
42 | };
43 |
44 | isModerator = (req, res, next) => {
45 | User.findByPk(req.userId).then(user => {
46 | user.getRoles().then(roles => {
47 | for (let i = 0; i < roles.length; i++) {
48 | if (roles[i].name === "moderator") {
49 | next();
50 | return;
51 | }
52 | }
53 |
54 | res.status(403).send({
55 | message: "Require Moderator Role!"
56 | });
57 | });
58 | });
59 | };
60 |
61 | isModeratorOrAdmin = (req, res, next) => {
62 | User.findByPk(req.userId).then(user => {
63 | user.getRoles().then(roles => {
64 | for (let i = 0; i < roles.length; i++) {
65 | if (roles[i].name === "moderator") {
66 | next();
67 | return;
68 | }
69 |
70 | if (roles[i].name === "admin") {
71 | next();
72 | return;
73 | }
74 | }
75 |
76 | res.status(403).send({
77 | message: "Require Moderator or Admin Role!"
78 | });
79 | });
80 | });
81 | };
82 |
83 | const authJwt = {
84 | verifyToken: verifyToken,
85 | isAdmin: isAdmin,
86 | isModerator: isModerator,
87 | isModeratorOrAdmin: isModeratorOrAdmin
88 | };
89 | module.exports = authJwt;
90 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/middleware/index.js:
--------------------------------------------------------------------------------
1 | const authJwt = require("./authJwt");
2 | const verifySignUp = require("./verifySignUp");
3 |
4 | module.exports = {
5 | authJwt,
6 | verifySignUp
7 | };
8 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/middleware/verifySignUp.js:
--------------------------------------------------------------------------------
1 | const db = require("../models");
2 | const ROLES = db.ROLES;
3 | const User = db.user;
4 |
5 | checkDuplicateUsernameOrEmail = (req, res, next) => {
6 | // Username
7 | User.findOne({
8 | where: {
9 | username: req.body.username
10 | }
11 | }).then(user => {
12 | if (user) {
13 | res.status(400).send({
14 | message: "Failed! Username is already in use!"
15 | });
16 | return;
17 | }
18 |
19 | // Email
20 | User.findOne({
21 | where: {
22 | email: req.body.email
23 | }
24 | }).then(user => {
25 | if (user) {
26 | res.status(400).send({
27 | message: "Failed! Email is already in use!"
28 | });
29 | return;
30 | }
31 |
32 | next();
33 | });
34 | });
35 | };
36 |
37 | checkRolesExisted = (req, res, next) => {
38 | if (req.body.roles) {
39 | for (let i = 0; i < req.body.roles.length; i++) {
40 | if (!ROLES.includes(req.body.roles[i])) {
41 | res.status(400).send({
42 | message: "Failed! Role does not exist = " + req.body.roles[i]
43 | });
44 | return;
45 | }
46 | }
47 | }
48 |
49 | next();
50 | };
51 |
52 | const verifySignUp = {
53 | checkDuplicateUsernameOrEmail: checkDuplicateUsernameOrEmail,
54 | checkRolesExisted: checkRolesExisted
55 | };
56 |
57 | module.exports = verifySignUp;
58 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/models/index.js:
--------------------------------------------------------------------------------
1 | const config = require("../config/db.config.js");
2 |
3 | const Sequelize = require("sequelize");
4 | const sequelize = new Sequelize(
5 | config.DB,
6 | config.USER,
7 | config.PASSWORD,
8 | {
9 | host: config.HOST,
10 | dialect: config.dialect,
11 | operatorsAliases: false,
12 |
13 | pool: {
14 | max: config.pool.max,
15 | min: config.pool.min,
16 | acquire: config.pool.acquire,
17 | idle: config.pool.idle
18 | }
19 | }
20 | );
21 |
22 | const db = {};
23 |
24 | db.Sequelize = Sequelize;
25 | db.sequelize = sequelize;
26 |
27 | db.user = require("../models/user.model.js")(sequelize, Sequelize);
28 | db.role = require("../models/role.model.js")(sequelize, Sequelize);
29 |
30 | db.role.belongsToMany(db.user, {
31 | through: "user_roles",
32 | foreignKey: "roleId",
33 | otherKey: "userId"
34 | });
35 | db.user.belongsToMany(db.role, {
36 | through: "user_roles",
37 | foreignKey: "userId",
38 | otherKey: "roleId"
39 | });
40 |
41 | db.ROLES = ["user", "admin", "moderator"];
42 |
43 | module.exports = db;
44 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/models/role.model.js:
--------------------------------------------------------------------------------
1 | module.exports = (sequelize, Sequelize) => {
2 | const Role = sequelize.define("roles", {
3 | id: {
4 | type: Sequelize.INTEGER,
5 | primaryKey: true
6 | },
7 | name: {
8 | type: Sequelize.STRING
9 | }
10 | });
11 |
12 | return Role;
13 | };
14 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/models/user.model.js:
--------------------------------------------------------------------------------
1 | module.exports = (sequelize, Sequelize) => {
2 | const User = sequelize.define("users", {
3 | username: {
4 | type: Sequelize.STRING
5 | },
6 | email: {
7 | type: Sequelize.STRING
8 | },
9 | password: {
10 | type: Sequelize.STRING
11 | }
12 | });
13 |
14 | return User;
15 | };
16 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/routes/auth.routes.js:
--------------------------------------------------------------------------------
1 | const { verifySignUp } = require("../middleware");
2 | const controller = require("../controllers/auth.controller");
3 |
4 | module.exports = function(app) {
5 | app.use(function(req, res, next) {
6 | res.header(
7 | "Access-Control-Allow-Headers",
8 | "x-access-token, Origin, Content-Type, Accept"
9 | );
10 | next();
11 | });
12 |
13 | app.post(
14 | "/api/auth/signup",
15 | [
16 | verifySignUp.checkDuplicateUsernameOrEmail,
17 | verifySignUp.checkRolesExisted
18 | ],
19 | controller.signup
20 | );
21 |
22 | app.post("/api/auth/signin", controller.signin);
23 | };
24 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/app/routes/user.routes.js:
--------------------------------------------------------------------------------
1 | const { authJwt } = require("../middleware");
2 | const controller = require("../controllers/user.controller");
3 |
4 | module.exports = function(app) {
5 | app.use(function(req, res, next) {
6 | res.header(
7 | "Access-Control-Allow-Headers",
8 | "x-access-token, Origin, Content-Type, Accept"
9 | );
10 | next();
11 | });
12 |
13 | app.get("/api/test/all", controller.allAccess);
14 |
15 | app.get(
16 | "/api/test/user",
17 | [authJwt.verifyToken],
18 | controller.userBoard
19 | );
20 |
21 | app.get(
22 | "/api/test/mod",
23 | [authJwt.verifyToken, authJwt.isModerator],
24 | controller.moderatorBoard
25 | );
26 |
27 | app.get(
28 | "/api/test/admin",
29 | [authJwt.verifyToken, authJwt.isAdmin],
30 | controller.adminBoard
31 | );
32 | };
33 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "node-js-jwt-auth",
3 | "version": "1.0.0",
4 | "description": "Node.js Token Based Authentication and Authorization",
5 | "main": "server.js",
6 | "scripts": {
7 | "start": "nodemon server.js",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "keywords": [
11 | "node.js",
12 | "jwt",
13 | "authentication",
14 | "express",
15 | "mysql"
16 | ],
17 | "author": "",
18 | "license": "ISC",
19 | "dependencies": {
20 | "bcryptjs": "^2.4.3",
21 | "body-parser": "^1.19.0",
22 | "cors": "^2.8.5",
23 | "express": "^4.17.1",
24 | "jsonwebtoken": "^8.5.1",
25 | "mysql2": "^2.1.0",
26 | "node-rest-client": "^3.1.0",
27 | "nodemon": "^2.0.4",
28 | "sequelize": "^5.21.3"
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/requests.rest:
--------------------------------------------------------------------------------
1 | ### Sign-Up
2 | POST http://localhost:8080/api/auth/signup
3 | Content-Type: application/json
4 |
5 | {
6 | "username": "john",
7 | "email": "john@gmail.com",
8 | "password": "12345678",
9 | "roles": ["moderator", "user"]
10 | }
11 |
12 |
13 | ### All User
14 | GET http://localhost:8080/api/test/all
15 |
16 |
17 | ### User Role
18 | GET http://localhost:8080/api/test/user
19 |
20 |
21 | ### Sign-In
22 | POST http://localhost:8080/api/auth/signin
23 | Content-Type: application/json
24 |
25 | {
26 | "username": "mod",
27 | "password": "12345678"
28 | }
29 |
--------------------------------------------------------------------------------
/node-jwt-mysql-auth/server.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const bodyParser = require("body-parser");
3 | const cors = require("cors");
4 |
5 | const app = express();
6 |
7 | var corsOptions = {
8 | origin: "http://localhost:8081"
9 | };
10 |
11 | app.use(cors(corsOptions));
12 |
13 | // parse requests of content-type - application/json
14 | app.use(bodyParser.json());
15 |
16 | // parse requests of content-type - application/x-www-form-urlencoded
17 | app.use(bodyParser.urlencoded({ extended: true }));
18 |
19 | // database
20 | const db = require("./app/models");
21 | const Role = db.role;
22 |
23 | db.sequelize.sync();
24 | // force: true will drop the table if it already exists
25 | // db.sequelize.sync({force: true}).then(() => {
26 | // console.log('Drop and Resync Database with { force: true }');
27 | // initial();
28 | // });
29 |
30 | // simple route
31 | app.get("/", (req, res) => {
32 | res.json({ message: "Welcome to bezkoder application." });
33 | });
34 |
35 | // routes
36 | require('./app/routes/auth.routes')(app);
37 | require('./app/routes/user.routes')(app);
38 |
39 | // set port, listen for requests
40 | const PORT = process.env.PORT || 8080;
41 | app.listen(PORT, () => {
42 | console.log(`Server is running on port ${PORT}.`);
43 | });
44 |
45 | function initial() {
46 | Role.create({
47 | id: 1,
48 | name: "user"
49 | });
50 |
51 | Role.create({
52 | id: 2,
53 | name: "moderator"
54 | });
55 |
56 | Role.create({
57 | id: 3,
58 | name: "admin"
59 | });
60 | }
--------------------------------------------------------------------------------
/nodejs-api.md:
--------------------------------------------------------------------------------
1 | # Node APIs List
2 |
3 | - [Global Objects](#global-objects)
4 | - [Console](#console)
5 | - [Timers](#timers)
6 | - [Modules](#modules)
7 | - [Process](#process)
8 | - [Child Process](#child-process)
9 | - [Util](#util)
10 | - [Events](#events)
11 | - [Stream](#stream)
12 | - [File System](#file-system)
13 | - [Path](#path)
14 | - [HTTP](#http)
15 | - [URL](#url)
16 | - [Query String](#query-string)
17 | - [Assert](#assert)
18 | - [OS](#os)
19 | - [Buffer](#buffer)
20 |
21 | ## Global Objects
22 |
23 | In browsers, the top-level scope is the global scope.
24 | That means that in browsers if you're in the global scope var something will define a global variable.
25 | In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
26 |
27 | | API | Description |
28 | |-------------|--------------|
29 | |__filename; | The filename of the code being executed. (absolute path)|
30 | |__dirname; | The name of the directory that the currently executing script resides in. (absolute path)|
31 | |module; | A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().
32 | |exports; | A reference to the module.exports that is shorter to type.|
33 | |process; | The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.|
34 | |Buffer; | The Buffer class is a global type for dealing with binary data directly.|
35 |
36 | ## Console
37 |
38 | | API | Description |
39 | |---------------------------------------|---------------------------------|
40 | |console.log([data], [...]); |Prints to stdout with newline.|
41 | |console.info([data], [...]); |Same as console.log.|
42 | |console.error([data], [...]); |Same as console.log but prints to stderr.|
43 | |console.warn([data], [...]); |Same as console.error.|
44 | |console.dir(obj); |Uses util.inspect on obj and prints resulting string to stdout.|
45 | |console.time(label); |Mark a time.|
46 | |console.timeEnd(label); |Finish timer, record output.|
47 | |console.trace(label); |Print a stack trace to stderr of the current position.|
48 | |console.assert(expression, [message]); |Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.|
49 |
50 | ## Timers
51 |
52 | | API | Description |
53 | |---------------------------------------------|-------------------------------------|
54 | |setTimeout(callback, delay, [arg], [...]); | To schedule execution of a one-time callback after delay milliseconds. Optionally you can also pass arguments to the callback.|
55 | |clearTimeout(t); | Stop a timer that was previously created with setTimeout().|
56 | |setInterval(callback, delay, [arg], [...]); | To schedule the repeated execution of callback every delay milliseconds. Optionally you can also pass arguments to the callback.|
57 | |clearInterval(t); | Stop a timer that was previously created with setInterval().|
58 | |setImmediate(callback, [arg], [...]); | To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval.|
59 | |clearImmediate(immediateObject); | Stop a timer that was previously created with setImmediate().|
60 | |unref(); | Allow you to create a timer that is active but if it is the only item left in the event loop, node won't keep the program running.|
61 | |ref(); | If you had previously unref()d a timer you can call ref() to explicitly request the timer hold the program open.
62 |
63 | ## Modules
64 |
65 | ```javascript
66 | var module = require('./module.js'); // Loads the module module.js in the same directory.
67 | module.require('./another_module.js'); // load another_module as if require() was called from the module itself.
68 | ```
69 |
70 | | API | Description |
71 | |---------------------------------------------|-------------------------------------|
72 | |module.id; |The identifier for the module. Typically this is the fully resolved filename.|
73 | |module.filename; |The fully resolved filename to the module.|
74 | |module.loaded; |Whether or not the module is done loading, or is in the process of loading.|
75 | |module.parent; |The module that required this one.|
76 | |module.children; |The module objects required by this one.|
77 |
78 | ```javascript
79 | exports.area = function (r) {
80 | return 3.14 * r * r;
81 | };
82 |
83 | // If you want the root of your module's export to be a function (such as a constructor)
84 | // or if you want to export a complete object in one assignment instead of building it one property at a time,
85 | // assign it to module.exports instead of exports.
86 | module.exports = function(width) {
87 | return {
88 | area: function() {
89 | return width * width;
90 | }
91 | };
92 | }
93 | ```
94 |
95 | ## Process
96 |
97 | ```javascript
98 | process.on('exit', function(code) {}); // Emitted when the process is about to exit
99 | process.on('uncaughtException', function(err) {}); // Emitted when an exception bubbles all the way back to the event loop. (should not be used)
100 | ```
101 |
102 | | API | Description |
103 | |--------------------------|-------------------------------------|
104 | |process.stdout; |A writable stream to stdout.|
105 | |process.stderr; |A writable stream to stderr.|
106 | |process.stdin; |A readable stream for stdin.|
107 | |process.argv; |An array containing the command line arguments.|
108 | |process.env; |An object containing the user environment.|
109 | |process.execPath; |This is the absolute pathname of the executable that started the process.|
110 | |process.execArgv; |This is the set of node-specific command line options from the executable that started the process.|
111 | |process.arch; |What processor architecture you're running on: 'arm', 'ia32', or 'x64'.|
112 | |process.config; |An Object containing the JavaScript representation of the configure options that were used to compile the current node executable.|
113 | |process.pid; |The PID of the process.|
114 | |process.platform; |What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'.|
115 | |process.title; |Getter/setter to set what is displayed in 'ps'.|
116 | |process.version; |A compiled-in property that exposes NODE_VERSION.|
117 | |process.versions; |A property exposing version strings of node and its dependencies.|
118 | |process.abort(); |This causes node to emit an abort. This will cause node to exit and generate a core file.|
119 | |process.chdir(dir); |Changes the current working directory of the process or throws an exception if that fails.|
120 | |process.cwd(); |Returns the current working directory of the process.|
121 | |process.exit([code]); |Ends the process with the specified code. If omitted, exit uses the 'success' code 0.|
122 | |process.getgid(); |Gets the group identity of the process.|
123 | |process.setgid(id); |Sets the group identity of the process.|
124 | |process.getuid(); |Gets the user identity of the process.|
125 | |process.setuid(id); |Sets the user identity of the process.|
126 | |process.getgroups(); |Returns an array with the supplementary group IDs.|
127 | |process.setgroups(grps); |Sets the supplementary group IDs.|
128 | |process.initgroups(user, extra_grp); | Reads /etc/group and initializes the group access list, using all groups of which the user is a member.|
129 | |process.kill(pid, [signal]); |Send a signal to a process. pid is the process id and signal is the string describing the signal to send.|
130 | |process.memoryUsage(); |Returns an object describing the memory usage of the Node process measured in bytes.|
131 | |process.nextTick(callback); |On the next loop around the event loop call this callback.|
132 | |process.maxTickDepth; |Callbacks passed to process.nextTick will usually be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously.|
133 | |process.umask([mask]); |Sets or reads the process's file mode creation mask.|
134 | |process.uptime(); |Number of seconds Node has been running.|
135 | |process.hrtime(); |Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.|
136 |
137 | ## Child Process
138 |
139 | Node provides a tri-directional popen facility through the child_process module.
140 | It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way.
141 |
142 | | API | Description |
143 | |--------------------------|--------------------------------------|
144 | ChildProcess; |Class. ChildProcess is an EventEmitter|
145 | child.stdin; |A Writable Stream that represents the child process's stdin|
146 | child.stdout; |A Readable Stream that represents the child process's stdout|
147 | child.stderr; |A Readable Stream that represents the child process's stderr.|
148 | child.pid; |The PID of the child process|
149 | child.connected; |If .connected is false, it is no longer possible to send messages|
150 | child.kill([signal]); |Send a signal to the child process|
151 | child.send(message, [sendHandle]); |When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.|
152 | child.disconnect(); | Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive.|
153 | child_process.spawn(command, [args], [options]); |Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.|
154 | child_process.exec(command, [options], callback); |Runs a command in a shell and buffers the output.|
155 | child_process.execFile(file, [args], [options], [callback]); |Runs a command in a shell and buffers the output.|
156 | child_process.fork(modulePath, [args], [options]); |This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in. |
157 |
158 | ## Util
159 |
160 | These functions are in the module 'util'. Use require('util') to access them.
161 |
162 | | API | Description |
163 | |-----------------------------|--------------------------------------|
164 | |util.format(format, [...]); |Returns a formatted string using the first argument as a printf-like format. (%s, %d, %j)|
165 | |util.debug(string); |A synchronous output function. Will block the process and output string immediately to stderr|
166 | |util.error([...]); |Same as util.debug() except this will output all arguments immediately to stderr.|
167 | |util.puts([...]); |A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.|
168 | |util.print([...]); |A synchronous output function. Will block the process, cast each argument to a string then output to stdout. (no newlines)|
169 | |util.log(string); |Output with timestamp on stdout.|
170 | |util.inspect(object, [opts]); |Return a string representation of object, which is useful for debugging. (options: showHidden, depth, colors, customInspect)|
171 | |util.isArray(object); |Returns true if the given "object" is an Array. false otherwise.|
172 | |util.isRegExp(object); |Returns true if the given "object" is a RegExp. false otherwise.|
173 | |util.isDate(object); |Returns true if the given "object" is a Date. false otherwise.|
174 | |util.isError(object); |Returns true if the given "object" is an Error. false otherwise.|
175 | |util.inherits(constructor, superConstructor); |Inherit the prototype methods from one constructor into another.|
176 |
177 | ## Events
178 |
179 | All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");
180 | To access the EventEmitter class, require('events').EventEmitter.
181 | All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.
182 |
183 | | API | Description |
184 | |---------------------------------------|--------------------------------------|
185 | |emitter.addListener(event, listener); |Adds a listener to the end of the listeners array for the specified event.|
186 | |emitter.on(event, listener); |Same as emitter.addListener().|
187 | |emitter.once(event, listener); |Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.|
188 | |emitter.removeListener(event, listener); |Remove a listener from the listener array for the specified event.|
189 | |emitter.removeAllListeners([event]); |Removes all listeners, or those of the specified event.|
190 | |emitter.setMaxListeners(n); |By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.|
191 | |emitter.listeners(event); |Returns an array of listeners for the specified event.|
192 | |emitter.emit(event, [arg1], [arg2], [...]); |Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise.|
193 | |EventEmitter.listenerCount(emitter, event); |Return the number of listeners for a given event.|
194 |
195 | ## Stream
196 |
197 | A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable, writable, or both. All streams are instances of EventEmitter.
198 |
199 | The Readable stream interface is the abstraction for a source of data that you are reading from.
200 | In other words, data comes out of a Readable stream.
201 | A Readable stream will not start emitting data until you indicate that you are ready to receive it.
202 | Examples of readable streams include: http responses on the client, http requests on the server, fs read streams
203 | zlib streams, crypto streams, tcp sockets, child process stdout and stderr, process.stdin.
204 |
205 | ```javascript
206 | var readable = getReadableStreamSomehow();
207 | ```
208 |
209 | | API | Description |
210 | |---------------------------------------|--------------------------------------|
211 | |readable.on('readable', function() {}); |When a chunk of data can be read from the stream, it will emit a 'readable' event|
212 | |readable.on('data', function(chunk) {}); |If you attach a data event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available.|
213 | |readable.on('end', function() {}); |This event fires when there will be no more data to read.|
214 | |readable.on('close', function() {}); |Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this.|
215 | |readable.on('error', function() {}); |Emitted if there was an error receiving data.|
216 | |readable.setEncoding(encoding); |Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.|
217 | |readable.resume(); |This method will cause the readable stream to resume emitting data events.|
218 | |readable.pause(); |This method will cause a stream in flowing-mode to stop emitting data events.|
219 | |readable.pipe(destination, [options]); |This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream|
220 | |readable.unpipe([destination]); |This method will remove the hooks set up for a previous pipe() call. If the destination is not specified, then all pipes are removed.|
221 | |readable.unshift(chunk); |This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.|
222 |
223 | The Writable stream interface is an abstraction for a destination that you are writing data to.
224 | Examples of writable streams include: http requests on the client, http responses on the server, fs write streams,
225 | zlib streams, crypto streams, tcp sockets, child process stdin, process.stdout, process.stderr.
226 |
227 | ```javascript
228 | var writer = getWritableStreamSomehow();
229 | ```
230 |
231 | | API | Description |
232 | |------------------------------------------------|--------------------------------------|
233 | |writable.write(chunk, [encoding], [callback]); | This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.|
234 | |writer.once('drain', write); |If a writable.write(chunk) call returns false, then the drain event will indicate when it is appropriate to begin writing more data to the stream.|
235 | |writable.end([chunk], [encoding], [callback]); |Call this method when no more data will be written to the stream.|
236 | |writer.on('finish', function() {}); |When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.|
237 | |writer.on('pipe', function(src) {}); |This is emitted whenever the pipe() method is called on a readable stream, adding this writable to its set of destinations.|
238 | |writer.on('unpipe', function(src) {}); |This is emitted whenever the unpipe() method is called on a readable stream, removing this writable from its set of destinations.|
239 | |writer.on('error', function(src) {}); |Emitted if there was an error when writing or piping data.|
240 |
241 |
242 | Duplex streams are streams that implement both the Readable and Writable interfaces. See above for usage.
243 | Examples of Duplex streams include: tcp sockets, zlib streams, crypto streams.
244 |
245 | Transform streams are Duplex streams where the output is in some way computed from the input. They implement both the Readable and Writable interfaces. See above for usage.
246 |
247 | Examples of Transform streams include: zlib streams, crypto streams.
248 |
249 | ## File System
250 |
251 | To use this module do require('fs').
252 | All the methods have asynchronous and synchronous forms.
253 |
254 | | API | Description |
255 | |------------------------------------------------|--------------------------------------|
256 | |fs.rename(oldPath, newPath, callback); |Asynchronous rename. No arguments other than a possible exception are given to |the completion callback.Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.|
257 | |fs.renameSync(oldPath, newPath); | Synchronous rename.|
258 | |fs.ftruncate(fd, len, callback); | Asynchronous ftruncate. No arguments other than a possible exception are given to |the completion callback.|
259 | |fs.ftruncateSync(fd, len); | Synchronous ftruncate.|
260 | |fs.truncate(path, len, callback); | Asynchronous truncate. No arguments other than a possible exception are given to the completion callback.|
261 | |fs.truncateSync(path, len); | Synchronous truncate.|
262 | |fs.chown(path, uid, gid, callback); | Asynchronous chown. No arguments other than a possible exception are given to the |completion callback.|
263 | |fs.chownSync(path, uid, gid); | Synchronous chown.|
264 | |fs.fchown(fd, uid, gid, callback); | Asynchronous fchown. No arguments other than a possible exception are given to the completion callback.|
265 | |fs.fchownSync(fd, uid, gid); | Synchronous fchown.|
266 | |fs.lchown(path, uid, gid, callback); | Asynchronous lchown. No arguments other than a possible exception are given to the completion callback.|
267 | |fs.lchownSync(path, uid, gid); | Synchronous lchown.|
268 | |fs.chmod(path, mode, callback); | Asynchronous chmod. No arguments other than a possible exception are given to the completion callback.|
269 | |fs.chmodSync(path, mode); | Synchronous chmod.|
270 | |fs.fchmod(fd, mode, callback); | Asynchronous fchmod. No arguments other than a possible exception are given to the completion callback.|
271 | |fs.fchmodSync(fd, mode); | Synchronous fchmod.|
272 | |fs.lchmod(path, mode, callback); | Asynchronous lchmod. No arguments other than a possible exception are given to the completion callback.|
273 | |fs.lchmodSync(path, mode); | Synchronous lchmod.|
274 | |fs.stat(path, callback); | Asynchronous stat. The callback gets two arguments (err, stats) where stats is a fs.Stats object.|
275 | |fs.statSync(path); | Synchronous stat. Returns an instance of fs.Stats.|
276 | |fs.lstat(path, callback); | Asynchronous lstat. The callback gets two arguments (err, stats) where stats is a |fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.|
277 | |fs.lstatSync(path); | Synchronous lstat. Returns an instance of fs.Stats.|
278 | |fs.fstat(fd, callback); | Asynchronous fstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.|
279 | |fs.fstatSync(fd); | Synchronous fstat. Returns an instance of fs.Stats.|
280 | |fs.link(srcpath, dstpath, callback); | Asynchronous link. No arguments other than a possible exception are given to the completion callback.|
281 | |fs.linkSync(srcpath, dstpath); | Synchronous link.|
282 | |fs.symlink(srcpath, dstpath, [type], callback); | Asynchronous symlink. No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms)|
283 | |fs.symlinkSync(srcpath, dstpath, [type]); | Synchronous symlink.|
284 | |fs.readlink(path, callback); | Asynchronous readlink. The callback gets two arguments (err, linkString).|
285 | |fs.readlinkSync(path); | Synchronous readlink. Returns the symbolic link's string value.|
286 | |fs.unlink(path, callback); | Asynchronous unlink. No arguments other than a possible exception are given to the completion callback.|
287 | |fs.unlinkSync(path); | Synchronous unlink.|
288 | |fs.realpath(path, [cache], callback); | Asynchronous realpath. The callback gets two arguments (err, resolvedPath).|
289 | |fs.realpathSync(path, [cache]); | Synchronous realpath. Returns the resolved path.|
290 | |fs.rmdir(path, callback); | Asynchronous rmdir. No arguments other than a possible exception are given to the completion callback.|
291 | |fs.rmdirSync(path); | Synchronous rmdir.|
292 | |fs.mkdir(path, [mode], callback); | Asynchronous mkdir. No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.|
293 | |fs.mkdirSync(path, [mode]); | Synchronous mkdir.
294 | |fs.readdir(path, callback); | Asynchronous readdir. Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.|
295 | |fs.readdirSync(path); | Synchronous readdir. Returns an array of filenames excluding '.' and '..'.|
296 | |fs.close(fd, callback); | Asynchronous close. No arguments other than a possible exception are given to the completion callback.|
297 | |fs.closeSync(fd); | Synchronous close.|
298 | |fs.open(path, flags, [mode], callback); | Asynchronous file open.|
299 | |fs.openSync(path, flags, [mode]); | Synchronous version of fs.open().|
300 | |fs.utimes(path, atime, mtime, callback); | Change file timestamps of the file referenced by the supplied path.|
301 | |fs.utimesSync(path, atime, mtime); | Synchronous version of fs.utimes().|
302 | |fs.futimes(fd, atime, mtime, callback); | Change the file timestamps of a file referenced by the supplied file descriptor|
303 | |fs.futimesSync(fd, atime, mtime); | Synchronous version of fs.futimes().|
304 | |fs.fsync(fd, callback); | Asynchronous fsync. No arguments other than a possible exception are given to the completion callback.|
305 | |fs.fsyncSync(fd); |Synchronous fsync.|
306 | |fs.write(fd, buffer, offset, length, position, callback); | Write buffer to the file specified by fd.|
307 | |fs.writeSync(fd, buffer, offset, length, position); | Synchronous version of fs.write(). Returns the number of bytes written.|
308 | |fs.read(fd, buffer, offset, length, position, callback); | Read data from the file specified by fd.|
309 | |fs.readSync(fd, buffer, offset, length, position); | Synchronous version of fs.read. Returns the number of bytesRead.|
310 | |fs.readFile(filename, [options], callback); | Asynchronously reads the entire contents of a file.|
311 | |fs.readFileSync(filename, [options]); | Synchronous version of fs.readFile. Returns the contents of the filename. If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.|
312 | |fs.writeFile(filename, data, [options], callback); |Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.|
313 | |fs.writeFileSync(filename, data, [options]); | The synchronous version of fs.writeFile.|
314 | |fs.appendFile(filename, data, [options], callback); | Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.|
315 | |fs.appendFileSync(filename, data, [options]); | The synchronous version of fs.appendFile.|
316 | |fs.watch(filename, [options], [listener]); | Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher. The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename is the name of the file which triggered the event.|
317 | |fs.exists(path, callback); | Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. (should not be used)|
318 | |fs.existsSync(path); |Synchronous version of fs.exists. (should not be used)|
319 | |fs.Stats: |objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.|
320 | |stats.isFile();| |
321 | |stats.isDirectory()| |
322 | |stats.isBlockDevice()| |
323 | |stats.isCharacterDevice()| |
324 | |stats.isSymbolicLink() |(only valid with fs.lstat())|
325 | |stats.isFIFO()| |
326 | |stats.isSocket()| |
327 |
328 | ```javascript
329 | fs.createReadStream(path, [options]); // Returns a new ReadStream object.
330 | fs.createWriteStream(path, [options]); // Returns a new WriteStream object.
331 | ```
332 |
333 | ## Path
334 |
335 | Use require('path') to use this module.
336 | This module contains utilities for handling and transforming file paths.
337 | Almost all these methods perform only string transformations.
338 | The file system is not consulted to check whether paths are valid.
339 |
340 | | API | Description |
341 | |------------------------------------------------|--------------------------------------|
342 | |path.normalize(p); |Normalize a string path, taking care of '..' and '.' parts.|
343 | |path.join([path1], [path2], [...]); |Join all arguments together and normalize the resulting path.|
344 | |path.resolve([from ...], to); |Resolves 'to' to an absolute path.|
345 | |path.relative(from, to); |Solve the relative path from 'from' to 'to'.|
346 | |path.dirname(p); |Return the directory name of a path. Similar to the Unix dirname command.|
347 | |path.basename(p, [ext]); |Return the last portion of a path. Similar to the Unix basename command.|
348 | |path.extname(p); |Return the extension of the path, from the last '.' to end of string in the last portion of the path.|
349 | |path.sep; |The platform-specific file separator. '\\' or '/'.|
350 | |path.delimiter; |The platform-specific path delimiter, ';' or ':'.|
351 |
352 | ## HTTP
353 |
354 | To use the HTTP server and client one must require('http').
355 |
356 | | API | Description |
357 | |------------------------------------------------|--------------------------------------|
358 | |http.STATUS_CODES; |A collection of all the standard HTTP response status codes, and the short description of each.|
359 | |http.request(options, [callback]); |This function allows one to transparently issue requests.|
360 | |http.get(options, [callback]); |Set the method to GET and calls req.end() automatically.|
361 | |server = http.createServer([requestListener]); |Returns a new web server object. The requestListener is a function which is automatically added to the 'request' event.|
362 | |server.listen(port, [hostname], [backlog], [callback]); |Begin accepting connections on the specified port and hostname|
363 | |server.listen(path, [callback]); |Start a UNIX socket server listening for connections on the given path.|
364 | |server.listen(handle, [callback]); |The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: } object.|
365 | |server.close([callback]); |Stops the server from accepting new connections. |
366 | |server.setTimeout(msecs, callback); |Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.|
367 | |server.maxHeadersCount; |Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.|
368 | |server.timeout; |The number of milliseconds of inactivity before a socket is presumed to have timed out.|
369 | |server.on('request', function (request, response) { }); |Emitted each time there is a request.|
370 | |server.on('connection', function (socket) { }); |When a new TCP stream is established.|
371 | |server.on('close', function () { }); |Emitted when the server closes.|
372 | |server.on('checkContinue', function (request, response) { }); |Emitted each time a request with an http Expect: 100-continue is received.|
373 | |server.on('connect', function (request, socket, head) { }); |Emitted each time a client requests a http CONNECT method.|
374 | |server.on('upgrade', function (request, socket, head) { }); |Emitted each time a client requests a http upgrade.|
375 | |server.on('clientError', function (exception, socket) { }); |If a client connection emits an 'error' event - it will forwarded here.|
376 | |request.write(chunk, [encoding]); |Sends a chunk of the body.|
377 | |request.end([data], [encoding]); |Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream.|
378 | |request.abort(); |Aborts a request.|
379 | |request.setTimeout(timeout, [callback]); |Once a socket is assigned to this request and is connected socket.setTimeout() will be called.|
380 | |request.setNoDelay([noDelay]); |Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.|
381 | |request.setSocketKeepAlive([enable], [initialDelay]); |Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.|
382 | |request.on('response', function(response) { }); |Emitted when a response is received to this request. This event is emitted only once.|
383 | |request.on('socket', function(socket) { }); |Emitted after a socket is assigned to this request.|
384 | |request.on('connect', function(response, socket, head) { }); |Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections |closed.|
385 | |request.on('upgrade', function(response, socket, head) { }); |Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.|
386 | |request.on('continue', function() { }); |Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.|
387 | |response.write(chunk, [encoding]); | This sends a chunk of the response body. If this merthod is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.|
388 | |response.writeContinue(); |Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.|
389 | |response.writeHead(statusCode, [reasonPhrase], [headers]); |Sends a response header to the request.|
390 | |response.setTimeout(msecs, callback); | Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.|
391 | |response.setHeader(name, value); | Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.|
392 | |response.getHeader(name); |Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive.|
393 | |response.removeHeader(name); |Removes a header that's queued for implicit sending.|
394 | |response.addTrailers(headers); |This method adds HTTP trailing headers (a header but at the end of the message) to the response.|
395 | |response.end([data], [encoding]); |This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.|
396 | |response.statusCode; |When using implicit headers (not calling response.writeHead|() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.|
397 | |response.headersSent; | Boolean (read-only). True if headers were sent, false otherwise.|
398 | |response.sendDate; | When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.|
399 | |response.on('close', function () { }); | Indicates that the underlying connection was terminated before response.end() was called or able to flush.|
400 | |response.on('finish', function() { }); |Emitted when the response has been sent. |
401 | |message.httpVersion; |In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server.|
402 | |message.headers; |The request/response headers object.|
403 | |message.trailers; |The request/response trailers object. Only populated after the 'end' event.|
404 | |message.method; |The request method as a string. Read only. Example: 'GET', 'DELETE'.|
405 | |message.url; |Request URL string. This contains only the URL that is present in the actual HTTP request.|
406 | |message.statusCode; |The 3-digit HTTP response status code. E.G. 404.|
407 | |message.socket; |The net.Socket object associated with the connection.|
408 | |message.setTimeout(msecs, callback); |Calls message.connection.setTimeout(msecs, callback).|
409 |
410 | ## URL
411 |
412 | This module has utilities for URL resolution and parsing. Call require('url') to use it.
413 |
414 | | API | Description |
415 | |------------------------------------------------|--------------------------------------|
416 | |url.parse(urlStr, [parseQueryString], [slashesDenoteHost]); |Take a URL string, and return an object.|
417 | |url.format(urlObj); |Take a parsed URL object, and return a formatted URL string.|
418 | |url.resolve(from, to); |Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.|
419 |
420 | ## Query String
421 |
422 | This module provides utilities for dealing with query strings. Call require('querystring') to use it.
423 |
424 | | API | Description |
425 | |------------------------------------------------|--------------------------------------|
426 | |querystring.stringify(obj, [sep], [eq]); | Serialize an object to a query string. Optionally override the default separator ('&') and assignment ('=') characters.|
427 | |querystring.parse(str, [sep], [eq], [options]); | Deserialize a query string to an object. Optionally override the default |separator ('&') and assignment ('=') characters.|
428 |
429 | ## Assert
430 |
431 | This module is used for writing unit tests for your applications, you can access it with require('assert').
432 |
433 | | API | Description |
434 | |----------------------------------------------------|--------------------------------------|
435 | |assert.fail(actual, expected, message, operator); |Throws an exception that displays the values for actual and expected separated by the provided operator.|
436 | |assert(value, message); assert.ok(value, [message]); |Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);|
437 | |assert.equal(actual, expected, [message]); |Tests shallow, coercive equality with the equal comparison operator |( == ).|
438 | |assert.notEqual(actual, expected, [message]); |Tests shallow, coercive non-equality with the not equal comparison operator ( != ).|
439 | |assert.deepEqual(actual, expected, [message]); |Tests for deep equality.|
440 | |assert.notDeepEqual(actual, expected, [message]); |Tests for any deep inequality.|
441 | |assert.strictEqual(actual, expected, [message]); |Tests strict equality, as determined by the strict equality operator ( === )|
442 | |assert.notStrictEqual(actual, expected, [message]); |Tests strict non-equality, as determined by the strict not equal operator ( !== )|
443 | |assert.throws(block, [error], [message]); |Expects block to throw an error. error can be constructor, RegExp or validation function.|
444 | |assert.doesNotThrow(block, [message]); |Expects block not to throw an error, see assert.throws for details.|
445 | |assert.ifError(value); |Tests if value is not a false value, throws if it is a true value. |Useful when testing the first argument, error in callbacks.|
446 |
447 | ## OS
448 |
449 | Provides a few basic operating-system related utility functions.
450 | Use require('os') to access this module.
451 |
452 | | API | Description |
453 | |-------------------------|--------------------------------------|
454 | |os.tmpdir(); |Returns the operating system's default directory for temp files.
455 | |os.endianness(); |Returns the endianness of the CPU. Possible values are "BE" or "LE".
456 | |os.hostname(); |Returns the hostname of the operating system.
457 | |os.type(); |Returns the operating system name.
458 | |os.platform(); |Returns the operating system platform.
459 | |os.arch(); |Returns the operating system CPU architecture.
460 | |os.release(); |Returns the operating system release.
461 | |os.uptime(); |Returns the system uptime in seconds.
462 | |os.loadavg(); |Returns an array containing the 1, 5, and 15 minute load averages.
463 | |os.totalmem(); |Returns the total amount of system memory in bytes.
464 | |os.freemem(); |Returns the amount of free system memory in bytes.
465 | |os.cpus(); |Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).
466 | |os.networkInterfaces(); |Get a list of network interfaces.
467 | |os.EOL; |A constant defining the appropriate End-of-line marker for the operating system.
468 |
469 | ## Buffer
470 |
471 | Buffer is used to dealing with binary data. Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap
472 |
473 | | API | Description |
474 | |-------------------------|--------------------------------------|
475 | |new Buffer(size); |Allocates a new buffer of size octets.|
476 | |new Buffer(array); |Allocates a new buffer using an array of octets.|
477 | |new Buffer(str, [encoding]); |Allocates a new buffer containing the given str. encoding defaults to 'utf8'.|
478 | |Buffer.isEncoding(encoding); |Returns true if the encoding is a valid encoding argument, or false otherwise.|
479 | |Buffer.isBuffer(obj); |Tests if obj is a Buffer|
480 | |Buffer.concat(list, [totalLength]); |Returns a buffer which is the result of concatenating |all the buffers in the list together.|
481 | |Buffer.byteLength(string, [encoding]); |Gives the actual byte length of a string.|
482 | |buf.write(string, [offset], [length], [encoding]); |Writes string to the buffer at offset using the given encoding|
483 | |buf.toString([encoding], [start], [end]); |Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start (defaults to 0) and ending at end (defaults to buffer.length).|
484 | |buf.toJSON(); |Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays|
485 | |buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]); |Does copy between buffers. The source and target regions can be overlapped|
486 | |buf.slice([start], [end]); |Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer. |
487 | |buf.fill(value, [offset], [end]); |Fills the buffer with the specified value|
488 | |buf[index]; |Get and set the octet at index|
489 | |buf.length; |The size of the buffer in bytes, Note that this is not necessarily the size of the contents|
490 | |buffer.INSPECT_MAX_BYTES; |How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.|
491 |
--------------------------------------------------------------------------------
/nodejs-basics/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 |
8 | # dependencies
9 | /node_modules
10 |
11 | # profiling files
12 | chrome-profiler-events.json
13 | speed-measure-plugin.json
14 |
15 | # IDEs and editors
16 | /.idea
17 | .project
18 | .classpath
19 | .c9/
20 | *.launch
21 | .settings/
22 | *.sublime-workspace
23 |
24 | # IDE - VSCode
25 | .vscode/*
26 | !.vscode/settings.json
27 | !.vscode/tasks.json
28 | !.vscode/launch.json
29 | !.vscode/extensions.json
30 |
31 | # misc
32 | /.sass-cache
33 | /connect.lock
34 | /coverage
35 | /libpeerconnection.log
36 | npm-debug.log
37 | yarn-error.log
38 | testem.log
39 | /typings
40 |
41 | # System Files
42 | .DS_Store
43 | Thumbs.db
44 |
--------------------------------------------------------------------------------
/nodejs-basics/assert.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Assert Module
3 | *
4 | * The assert module provides a simple set of assertion tests that can be used to test invariants.
5 | *
6 | */
7 |
8 | // Example: 01
9 | var assert = require('assert');
10 | function add (a, b) {
11 | return a + b;
12 | }
13 | var expected = add(10, 20);
14 | assert( expected === 30, 'Test Pass');
15 |
16 |
17 |
18 | // Example: 02
19 | var assert = require('assert');
20 | function add (a, b) {
21 | return a + b;
22 | }
23 | var expected = add(10, 20);
24 | assert( expected === 40, 'Test Fail!');
25 | // Output
26 | /*
27 | AssertionError [ERR_ASSERTION]: Test Fail!
28 | at Object. (C:\workspace\GitHub\nodejs-interview-questions\nodejs-basics\assert.js:24:1)
29 | at Module._compile (internal/modules/cjs/loader.js:776:30)
30 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
31 | at Module.load (internal/modules/cjs/loader.js:653:32)
32 | at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
33 | at Function.Module._load (internal/modules/cjs/loader.js:585:3)
34 | at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
35 | at startup (internal/bootstrap/node.js:283:19)
36 | at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
37 | */
38 |
--------------------------------------------------------------------------------
/nodejs-basics/buffer.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Buffer Object
3 | *
4 | * Buffer objects are used to represent binary data in the form of a sequence of bytes.
5 | *
6 | * Buffer class is used because pure javascript, while great with unicode-encoded strings,
7 | * does not handle straight binary data very well.
8 | *
9 | */
10 |
11 | // Example: Creates a zero-filled Buffer of length 10
12 | const buf = Buffer.alloc(10);
13 | console.log(buf);
14 | // Output:
15 |
16 |
17 |
18 | // Example: Buffer with Data
19 | const buf1 = Buffer.alloc(10);
20 | count = buf1.write("Alex");
21 | console.log("Octets written: "+ count);
22 | // Output: Octets written: 4
23 |
24 |
25 | // Example: Buffers and Character Encodings
26 | const buf2 = Buffer.from('Hello World', 'utf8');
27 | console.log(buf2);
28 | // Output:
29 |
30 | console.log(buf2.toString('hex'));
31 | // Output: 48656c6c6f20576f726c64
32 |
33 | console.log(buf2.toString('base64'));
34 | // Output: SGVsbG8gV29ybGQ=
35 |
36 |
37 | // Example: Buffers and iteration
38 | const buf3 = Buffer.from([1, 2, 3]);
39 |
40 | for (let b of buf3) {
41 | console.log(b);
42 | }
43 | // Output:
44 | // 1
45 | // 2
46 | // 3
--------------------------------------------------------------------------------
/nodejs-basics/callback.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Callback
3 | *
4 | * Callback is an asynchronous equivalent for a function.
5 | * It is called at the completion of each task.
6 | *
7 | */
8 |
9 |
10 | //-----------------
11 | // Blocking Code
12 | //-----------------
13 | var fs = require("fs");
14 | var data = fs.readFileSync('input.txt');
15 | console.log(data.toString());
16 | console.log("Program Ended!");
17 |
18 |
19 |
20 |
21 |
22 | //---------------------
23 | // Non Blocking Code
24 | //---------------------
25 | var fs = require("fs");
26 | fs.readFile('input.txt', function (err, data) {
27 | if (err) return console.error(err);
28 | console.log(data.toString());
29 | });
30 | console.log("Program Ended!!");
31 |
--------------------------------------------------------------------------------
/nodejs-basics/child-process-support.js:
--------------------------------------------------------------------------------
1 | console.log("Child Process " + process.argv[2] + " executed." );
2 |
--------------------------------------------------------------------------------
/nodejs-basics/child-process.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Child Process
3 | *
4 | * This module provides the ability to spawn child processes in a similar manner to popen(3).
5 | *
6 | */
7 |
8 |
9 | /**
10 | * 1. child_process.exec()
11 | *
12 | * This method runs a command in a console and buffers the output.
13 | */
14 |
15 |
16 | // Example: It will execute two commands dir and mkdir child.
17 | // The dir command will display list of current directory and mkdir command will create a new directory.
18 | const exec = require('child_process').exec;
19 | exec('create_directory.bat', (err, stdout, stderr) => {
20 | if (err) {
21 | console.error(err);
22 | return;
23 | }
24 | console.log(stdout);
25 | });
26 |
27 |
28 |
29 | /**
30 | * 2. child_process.spawn()
31 | *
32 | * This method returns streams (stdout & stderr) and it is generally used when the
33 | * process returns large amount of data.
34 | *
35 | */
36 |
37 | const child_process = require('child_process');
38 | for(var i = 0; i < 5; i++) {
39 | var workerProcess = child_process.spawn('node', ['child-process-support.js', i]);
40 | workerProcess.stdout.on('data', function (data) {
41 | console.log('stdout: ' + data);
42 | });
43 | workerProcess.stderr.on('data', function (data) {
44 | console.log('stderr: ' + data);
45 | });
46 | workerProcess.on('close', function (code) {
47 | console.log('child process exited with code ' + code);
48 | });
49 | }
50 |
51 |
52 | /**
53 | * 3. child_process.fork()
54 | *
55 | * This method is a special case of the spawn() to create Node processes.
56 | * This method returns object with a built-in communication channel in addition
57 | * to having all the methods in a normal ChildProcess instance.
58 | *
59 | */
60 |
61 | const child_process = require('child_process');
62 | for(var i = 0; i < 5; i++) {
63 | var worker_process = child_process.fork("child-process-support.js", [i]);
64 | worker_process.on('close', function (code) {
65 | console.log('child process exited with code ' + code);
66 | });
67 | }
68 |
--------------------------------------------------------------------------------
/nodejs-basics/console.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Executing program in NodeJS
3 | *
4 | * $ node 01_console.js
5 | */
6 |
7 | //Example: Simple Console
8 | console.log('Hello World!');
9 |
10 |
11 | // Example: Warning Console
12 | const msg = 'Warning!';
13 | console.warn(`${msg} Something went wrong here.`);
14 |
15 |
16 | // Example: Error Console
17 | console.error('This is an example of error Message !');
18 |
19 |
20 | // Example: Formatted Text
21 | console.log('Hello \t', 'World!');
22 |
23 |
24 | // Example: Custom Error
25 | //console.error(new Error('Hell! This is a wrong method.'));
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/nodejs-basics/create_directory.bat:
--------------------------------------------------------------------------------
1 | dir
2 | mkdir child
--------------------------------------------------------------------------------
/nodejs-basics/crypto.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Crypto Module
3 | *
4 | * It provides cryptographic functionality that includes a set of wrappers
5 | * for open SSL's hash HMAC, cipher, decipher, sign and verify functions.
6 | *
7 | **/
8 |
9 | const crypto = require('crypto');
10 |
11 |
12 | // Example: Encryption using Hash and HMAC
13 | const secret = 'abc';
14 | const hash = crypto.createHmac('sha256', secret)
15 | .update('Welcome to Cryptographic')
16 | .digest('hex');
17 | console.log(hash);
18 |
19 |
20 |
21 |
22 | // Example: Encryption using Cipher
23 | const cipher = crypto.createCipher('aes192', 'a password');
24 | var encrypted = cipher.update('Hello World!', 'utf8', 'hex');
25 | encrypted += cipher.final('hex');
26 | console.log(encrypted);
27 |
28 |
29 |
30 | // Example: Decryption using Decipher
31 | const decipher = crypto.createDecipher('aes192', 'a password');
32 | var encrypted = '9b1ade607555ef67592fa7334713cebd';
33 | var decrypted = decipher.update(encrypted, 'hex', 'utf8');
34 | decrypted += decipher.final('utf8');
35 | console.log(decrypted);
--------------------------------------------------------------------------------
/nodejs-basics/debugger.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Debugger Module
3 | *
4 | * Node.js includes an out-of-process debugging utility accessible via a V8 Inspector
5 | * and built-in debugging client.
6 | *
7 | * To use it, start Node.js with the inspect argument followed by the path to the script
8 | * to debug; a prompt will be displayed indicating successful launch of the debugger:
9 | *
10 | */
11 |
12 | global.x = 5;
13 | setTimeout(() => {
14 | debugger;
15 | console.log('World');
16 | }, 1000);
17 | console.log('Hello');
18 |
19 | /**
20 | * $ node inspect debugger.js
21 | * $ node --inspect=127.0.0.1:9230 debugger.js
22 | */
--------------------------------------------------------------------------------
/nodejs-basics/dns.js:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * Domain Name System (DNS)s
4 | *
5 | */
6 |
7 |
8 | // Example: dns.lookup()
9 | const dns = require('dns');
10 | dns.lookup('www.nodejs.org', (err, addresses, family) => {
11 | //console.log('addresses:', addresses);
12 | //console.log('family:',family);
13 | });
14 | /**
15 | * --------
16 | * Output
17 | * --------
18 | * addresses: 104.20.22.46
19 | * family: 4
20 | *
21 | * */
22 |
23 |
24 | // Example: lookupService()
25 | dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
26 | console.log(hostname, service);
27 | });
28 | /**
29 | * --------
30 | * Output
31 | * --------
32 | * BLR-G24FSF2-10L.mm-ads.com ssh
33 | *
34 | * */
35 |
--------------------------------------------------------------------------------
/nodejs-basics/event.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Events
3 | *
4 | * Node.js is a single-threaded application, but it can support concurrency via
5 | * the concept of event and callbacks.
6 | *
7 | * Every API of Node.js is asynchronous and being single-threaded, they use async
8 | * function calls to maintain concurrency.
9 | *
10 | */
11 |
12 | var EventEmitter = require('events');
13 |
14 | class MyEmitter extends EventEmitter {}
15 |
16 | var myEmitter = new MyEmitter();
17 | myEmitter.on('event', () => {
18 | console.log('An event occurred!');
19 | });
20 | myEmitter.emit('event');
21 |
22 |
23 |
24 | //---------------
25 | // Error events
26 | //---------------
27 | var myEmitter = new MyEmitter();
28 | myEmitter.emit('error', new Error('whoops!'));
29 | // Throws and crashes Node.js
30 |
--------------------------------------------------------------------------------
/nodejs-basics/exception.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Exception Handling
3 | *
4 | */
5 |
6 | // ReferenceError: b is not defined
7 | try {
8 | let a = 1;
9 | let c = a + b;
10 | } catch (e) {
11 | console.log(e);
12 | }
13 |
14 |
--------------------------------------------------------------------------------
/nodejs-basics/exec.js:
--------------------------------------------------------------------------------
1 |
2 | // Example: Creating child process with exec() Module
3 | var exec = require('child_process').exec;
4 |
5 | exec('git version', function(err, stdout) {
6 | if (err) {
7 | throw err;
8 | }
9 | console.log('\n Git Version function executed. \n', stdout);
10 | });
11 |
--------------------------------------------------------------------------------
/nodejs-basics/fs-module.js:
--------------------------------------------------------------------------------
1 | /**
2 | * ---------------
3 | * File System
4 | * ---------------
5 | *
6 | * The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.
7 | *
8 | *
9 | * --------------------------------
10 | * Important method of fs module
11 | * --------------------------------
12 | *
13 | * ---------------------------------- ----------------------------------------
14 | * Method Description
15 | * ---------------------------------- ----------------------------------------
16 | * fs.readFile(fileName [,options], callback) Reads existing file.
17 | * fs.writeFile(filename, data[, options], callback) Writes to the file. If file exists then overwrite the content otherwise creates new file.
18 | * fs.open(path, flags[, mode], callback) Opens file for reading or writing.
19 | * fs.rename(oldPath, newPath, callback) Renames an existing file.
20 | * fs.chown(path, uid, gid, callback) Asynchronous chown.
21 | * fs.stat(path, callback) Returns fs.stat object which includes important file statistics.
22 | * fs.link(srcpath, dstpath, callback) Links file asynchronously.
23 | * fs.symlink(destination, path[, type], callback) Symlink asynchronously.
24 | * fs.rmdir(path, callback) Renames an existing directory.
25 | * fs.mkdir(path[, mode], callback) Creates a new directory.
26 | * fs.readdir(path, callback) Reads the content of the specified directory.
27 | * fs.utimes(path, atime, mtime, callback) Changes the timestamp of the file.
28 | * fs.exists(path, callback) Determines whether the specified file exists or not.
29 | * fs.access(path[, mode], callback) Tests a user's permissions for the specified file.
30 | * fs.appendFile(file, data[, options], callback) Appends new content to the existing file.
31 | *
32 | *
33 | *
34 | *
35 | * --------- -------------------------------------------------
36 | * Flag Description
37 | * --------- -------------------------------------------------
38 | * r Open file for reading. An exception occurs if the file does not exist.
39 | * r+ Open file for reading and writing. An exception occurs if the file does not exist.
40 | * rs Open file for reading in synchronous mode.
41 | * rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.
42 | * w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
43 | * wx Like 'w' but fails if path exists.
44 | * w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
45 | * wx+ Like 'w+' but fails if path exists.
46 | * a Open file for appending. The file is created if it does not exist.
47 | * ax Like 'a' but fails if path exists.
48 | * a+ Open file for reading and appending. The file is created if it does not exist.
49 | * ax+ Like 'a+' but fails if path exists.
50 | *
51 | */
52 |
53 | const fs = require('fs');
54 | const dir = __dirname;
55 | const path = dir + `\\assets\\temp.txt`;
56 |
57 |
58 | // Example: Reading a directory
59 | fs.readdir('./assets', (err, files) => {
60 | if (err) {
61 | throw err;
62 | }
63 | console.log(files);
64 | });
65 | console.log('Reading a Directory...');
66 |
67 |
68 | // Example: Open and Read file
69 | fs.open(path, 'r', function(err, fd) {
70 | if (err) {
71 | return console.error(err);
72 | }
73 |
74 | var buffr = new Buffer(1024);
75 | fs.read(fd, buffr, 0, buffr.length, 0, function(err, bytes) {
76 | if (err) throw err;
77 |
78 | // Print only read bytes to avoid junk.
79 | if (bytes > 0) {
80 | console.log(buffr.slice(0, bytes).toString());
81 | }
82 |
83 | // Close the opened file.
84 | fs.close(fd, function(err) {
85 | if (err) throw err;
86 | });
87 | });
88 | });
89 |
90 |
91 |
92 | // Example: Reading File Synchronously
93 | var data = fs.readFileSync(path, 'utf8');
94 | console.log(data);
95 |
96 |
97 | // Example: Renaming a file
98 | fs.rename(path+'\\assets\\temp.txt', path+'\\assets\\dummy.txt', err => {
99 | if (err) throw err;
100 | console.log('Rename complete');
101 | });
102 |
103 |
104 | // Example: Creating & Writing File
105 | fs.writeFile(dir + '\\assets\\test.txt', 'This is first paragraph!', function(err) {
106 | if (err) console.log(err);
107 | else console.log('Write operation complete.');
108 | });
109 |
110 |
111 | // Example: Append File Content
112 | fs.appendFile(dir + '\\assets\\test.txt', '\nThis is second paragraph!', function(err) {
113 | if (err) console.log(err);
114 | else console.log('Append operation complete.');
115 | });
116 |
117 |
118 | // Example: File Status
119 | fs.stat(path, (err, stats) => {
120 | if (err) throw err;
121 | console.log(`stats: ${JSON.stringify(stats)}`);
122 | });
123 |
124 |
125 | // Example: Deleting a file
126 | fs.unlink(path, err => {
127 | if (err) throw err;
128 | console.log(`Successfully deleted file: ${path}`);
129 | });
130 |
131 |
--------------------------------------------------------------------------------
/nodejs-basics/global-objects.js:
--------------------------------------------------------------------------------
1 | /**
2 | * ------------------
3 | * Global Objects
4 | * ------------------
5 | *
6 | * __dirname()
7 | * __filename()
8 | * clearTimeout(timeoutObject)
9 | * console()
10 | * exports()
11 | * global()
12 | * module()
13 | * Process()
14 | * require()
15 | * setTimeout(callback, delay[, ...args])
16 | * TextDecoder()
17 | * TextEncoder()
18 | * URL()
19 | *
20 | * */
21 |
22 | //----------------------
23 | // reqiure() Object
24 | //----------------------
25 | var path = require("path");
26 | console.log(`Rock on world from ${path.basename(__filename)}`); // Rock on world from global-objects.js
27 |
28 | const jsonData = require('./assets/file.json');
29 | console.log(jsonData);
30 |
31 |
32 | //-------------------------
33 | // dirname() & filename()
34 | //-------------------------
35 | console.log(`Current directory: ${__dirname}`);
36 | console.log(`Current directory: ${path.dirname(__filename)}`);
37 | console.log(`Current file: ${__filename}`);
38 |
--------------------------------------------------------------------------------
/nodejs-basics/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | NodeJS Web Server
7 |
8 |
9 |
10 |
11 |
12 |
13 | NodeJS Web Module Example!
14 |
15 |
--------------------------------------------------------------------------------
/nodejs-basics/input.txt:
--------------------------------------------------------------------------------
1 | Lorem Ipsum is simply dummy text of the printing and typesetting industry.
2 | Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
3 | when an unknown printer took a galley of type and scrambled it to make a type
4 | specimen book. It has survived not only five centuries, but also the leap into
5 | electronic typesetting, remaining essentially unchanged. It was popularised in
6 | the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
7 | and more recently with desktop publishing software like Aldus PageMaker including
8 | versions of Lorem Ipsum.
--------------------------------------------------------------------------------
/nodejs-basics/miscellaneous.js:
--------------------------------------------------------------------------------
1 | // The default operation of the path module varies based on the operating system on which a Node.js application is running.
2 | var path = require('path');
3 |
4 | // The util module is primarily designed to support the needs of Node.js' own internal APIs.
5 | var util = require('util');
6 |
7 | // The v8 module exposes APIs that are specific to the version of V8 built into the Node.js binary.
8 | var v8 = require('v8');
9 |
10 | util.log(path.basename(__filename));
11 |
12 | var dirUploads = path.join(__dirname, 'www', 'files', 'uploads');
13 |
14 | util.log(dirUploads);
15 | util.log(v8.getHeapStatistics());
16 |
--------------------------------------------------------------------------------
/nodejs-basics/net-client.js:
--------------------------------------------------------------------------------
1 | const net = require('net');
2 | const client = net.connect({port: 61466}, () => {//use same port of server
3 | console.log('connected to server!');
4 | client.write('world!\r\n');
5 | });
6 | client.on('data', (data) => {
7 | console.log(data.toString());
8 | client.end();
9 | });
10 | client.on('end', () => {
11 | console.log('disconnected from server');
12 | });
13 |
--------------------------------------------------------------------------------
/nodejs-basics/net-server.js:
--------------------------------------------------------------------------------
1 | /**
2 | * NET Module
3 | *
4 | * It provides an asynchronous network API for creating stream-based
5 | * TCP or IPC servers (net.createServer()) and clients (net.createConnection()).
6 | *
7 | * The Node.js net module contains functions for creating both servers and clients.
8 | */
9 |
10 | const net = require('net');
11 | var server = net.createServer((socket) => {
12 | socket.end('goodbye\n');
13 | }).on('error', (err) => {
14 | // handle errors here
15 | throw err;
16 | });
17 | // grab a random port.
18 | server.listen(() => {
19 | address = server.address();
20 | console.log('opened server on %j', address);
21 | });
--------------------------------------------------------------------------------
/nodejs-basics/os.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Node.js OS Module
3 | * provides some basic operating-system related utility functions.
4 | *
5 | */
6 | const os = require('os');
7 |
8 |
9 | // This methods returns the amount of free system memory in bytes.
10 | console.log("Free Memory: ", os.freemem() +' bytes');
11 |
12 |
13 | // This method returns the home directory of the current user.
14 | console.log("Home directory: ", os.homedir());
15 |
16 |
17 | // This method is used to returns the hostname of the operating system.
18 | console.log("Host Name: ", os.hostname());
19 |
20 |
21 | // This method returns the endianness of the cpu. Its possible values are 'BE' for big endian or 'LE' for little endian.
22 | console.log("Endianness(): ", os.endianness());
23 |
24 |
25 | // This method returns an array containing the 1, 5, and 15 minute load averages.
26 | // The load average is a time fraction taken by system activity, calculated by the operating system and
27 | // expressed as a fractional number.
28 | console.log("Loadavg(): ", os.loadavg());
29 |
30 |
31 | // This method returns the operating system platform of the running computer i.e.
32 | // 'darwin', 'win32','freebsd', 'linux', 'sunos' etc.
33 | console.log("Platform: ", os.platform());
34 |
35 |
36 | // This method returns the operating system release.
37 | console.log("Release: ", os.release());
38 |
39 |
40 | // This method returns the operating system's default directory for temporary files.
41 | console.log("Tmpdir: ", os.tmpdir());
42 |
43 |
44 | // This method returns the total amount of system memory in bytes.
45 | console.log("Totalmem: ", os.totalmem());
46 |
47 |
48 | // This method returns the operating system name.
49 | console.log("Type: ", os.type());
50 |
51 |
52 | // This method returns the system uptime in seconds.
53 | console.log("Uptime: ", os.uptime());
54 |
55 |
56 |
57 | // This method is used to fetch the operating system CPU architecture.
58 | console.log("Architecture: ",os.arch());
59 |
60 |
61 | // This method is used to fetch an array of objects containing information about each cpu/core installed:
62 | // model, speed (in MHz), and times.
63 | console.log("CPUs: \n",os.cpus());
64 |
65 |
66 | // This method returns a list of network interfaces.
67 | console.log("Network Interfaces : \n",os.networkInterfaces());
68 |
--------------------------------------------------------------------------------
/nodejs-basics/output.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learning-zone/nodejs-basics/b2e06277fb45616c3378fd31bf90c4fc3074144b/nodejs-basics/output.txt
--------------------------------------------------------------------------------
/nodejs-basics/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "requires": true,
3 | "lockfileVersion": 1,
4 | "dependencies": {
5 | "accepts": {
6 | "version": "1.3.7",
7 | "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
8 | "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
9 | "requires": {
10 | "mime-types": "~2.1.24",
11 | "negotiator": "0.6.2"
12 | }
13 | },
14 | "array-flatten": {
15 | "version": "1.1.1",
16 | "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
17 | "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
18 | },
19 | "bignumber.js": {
20 | "version": "9.0.0",
21 | "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
22 | "integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A=="
23 | },
24 | "body-parser": {
25 | "version": "1.19.0",
26 | "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
27 | "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==",
28 | "requires": {
29 | "bytes": "3.1.0",
30 | "content-type": "~1.0.4",
31 | "debug": "2.6.9",
32 | "depd": "~1.1.2",
33 | "http-errors": "1.7.2",
34 | "iconv-lite": "0.4.24",
35 | "on-finished": "~2.3.0",
36 | "qs": "6.7.0",
37 | "raw-body": "2.4.0",
38 | "type-is": "~1.6.17"
39 | }
40 | },
41 | "bytes": {
42 | "version": "3.1.0",
43 | "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
44 | "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg=="
45 | },
46 | "content-disposition": {
47 | "version": "0.5.3",
48 | "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz",
49 | "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==",
50 | "requires": {
51 | "safe-buffer": "5.1.2"
52 | }
53 | },
54 | "content-type": {
55 | "version": "1.0.4",
56 | "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
57 | "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA=="
58 | },
59 | "cookie": {
60 | "version": "0.4.0",
61 | "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz",
62 | "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg=="
63 | },
64 | "cookie-signature": {
65 | "version": "1.0.6",
66 | "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
67 | "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
68 | },
69 | "core-util-is": {
70 | "version": "1.0.2",
71 | "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
72 | "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
73 | },
74 | "debug": {
75 | "version": "2.6.9",
76 | "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
77 | "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
78 | "requires": {
79 | "ms": "2.0.0"
80 | }
81 | },
82 | "depd": {
83 | "version": "1.1.2",
84 | "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
85 | "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak="
86 | },
87 | "destroy": {
88 | "version": "1.0.4",
89 | "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
90 | "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
91 | },
92 | "ee-first": {
93 | "version": "1.1.1",
94 | "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
95 | "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
96 | },
97 | "encodeurl": {
98 | "version": "1.0.2",
99 | "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
100 | "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k="
101 | },
102 | "escape-html": {
103 | "version": "1.0.3",
104 | "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
105 | "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
106 | },
107 | "etag": {
108 | "version": "1.8.1",
109 | "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
110 | "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc="
111 | },
112 | "express": {
113 | "version": "4.17.1",
114 | "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz",
115 | "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==",
116 | "requires": {
117 | "accepts": "~1.3.7",
118 | "array-flatten": "1.1.1",
119 | "body-parser": "1.19.0",
120 | "content-disposition": "0.5.3",
121 | "content-type": "~1.0.4",
122 | "cookie": "0.4.0",
123 | "cookie-signature": "1.0.6",
124 | "debug": "2.6.9",
125 | "depd": "~1.1.2",
126 | "encodeurl": "~1.0.2",
127 | "escape-html": "~1.0.3",
128 | "etag": "~1.8.1",
129 | "finalhandler": "~1.1.2",
130 | "fresh": "0.5.2",
131 | "merge-descriptors": "1.0.1",
132 | "methods": "~1.1.2",
133 | "on-finished": "~2.3.0",
134 | "parseurl": "~1.3.3",
135 | "path-to-regexp": "0.1.7",
136 | "proxy-addr": "~2.0.5",
137 | "qs": "6.7.0",
138 | "range-parser": "~1.2.1",
139 | "safe-buffer": "5.1.2",
140 | "send": "0.17.1",
141 | "serve-static": "1.14.1",
142 | "setprototypeof": "1.1.1",
143 | "statuses": "~1.5.0",
144 | "type-is": "~1.6.18",
145 | "utils-merge": "1.0.1",
146 | "vary": "~1.1.2"
147 | }
148 | },
149 | "finalhandler": {
150 | "version": "1.1.2",
151 | "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz",
152 | "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==",
153 | "requires": {
154 | "debug": "2.6.9",
155 | "encodeurl": "~1.0.2",
156 | "escape-html": "~1.0.3",
157 | "on-finished": "~2.3.0",
158 | "parseurl": "~1.3.3",
159 | "statuses": "~1.5.0",
160 | "unpipe": "~1.0.0"
161 | }
162 | },
163 | "forwarded": {
164 | "version": "0.1.2",
165 | "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz",
166 | "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ="
167 | },
168 | "fresh": {
169 | "version": "0.5.2",
170 | "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
171 | "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
172 | },
173 | "http-errors": {
174 | "version": "1.7.2",
175 | "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz",
176 | "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==",
177 | "requires": {
178 | "depd": "~1.1.2",
179 | "inherits": "2.0.3",
180 | "setprototypeof": "1.1.1",
181 | "statuses": ">= 1.5.0 < 2",
182 | "toidentifier": "1.0.0"
183 | }
184 | },
185 | "iconv-lite": {
186 | "version": "0.4.24",
187 | "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
188 | "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
189 | "requires": {
190 | "safer-buffer": ">= 2.1.2 < 3"
191 | }
192 | },
193 | "inherits": {
194 | "version": "2.0.3",
195 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
196 | "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
197 | },
198 | "ipaddr.js": {
199 | "version": "1.9.1",
200 | "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
201 | "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
202 | },
203 | "isarray": {
204 | "version": "1.0.0",
205 | "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
206 | "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
207 | },
208 | "media-typer": {
209 | "version": "0.3.0",
210 | "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
211 | "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g="
212 | },
213 | "merge-descriptors": {
214 | "version": "1.0.1",
215 | "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
216 | "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E="
217 | },
218 | "methods": {
219 | "version": "1.1.2",
220 | "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
221 | "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4="
222 | },
223 | "mime": {
224 | "version": "1.6.0",
225 | "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
226 | "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg=="
227 | },
228 | "mime-db": {
229 | "version": "1.44.0",
230 | "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.44.0.tgz",
231 | "integrity": "sha512-/NOTfLrsPBVeH7YtFPgsVWveuL+4SjjYxaQ1xtM1KMFj7HdxlBlxeyNLzhyJVx7r4rZGJAZ/6lkKCitSc/Nmpg=="
232 | },
233 | "mime-types": {
234 | "version": "2.1.27",
235 | "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.27.tgz",
236 | "integrity": "sha512-JIhqnCasI9yD+SsmkquHBxTSEuZdQX5BuQnS2Vc7puQQQ+8yiP5AY5uWhpdv4YL4VM5c6iliiYWPgJ/nJQLp7w==",
237 | "requires": {
238 | "mime-db": "1.44.0"
239 | }
240 | },
241 | "ms": {
242 | "version": "2.0.0",
243 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
244 | "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
245 | },
246 | "mysql": {
247 | "version": "2.18.1",
248 | "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz",
249 | "integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==",
250 | "requires": {
251 | "bignumber.js": "9.0.0",
252 | "readable-stream": "2.3.7",
253 | "safe-buffer": "5.1.2",
254 | "sqlstring": "2.3.1"
255 | }
256 | },
257 | "negotiator": {
258 | "version": "0.6.2",
259 | "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
260 | "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
261 | },
262 | "on-finished": {
263 | "version": "2.3.0",
264 | "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
265 | "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
266 | "requires": {
267 | "ee-first": "1.1.1"
268 | }
269 | },
270 | "parseurl": {
271 | "version": "1.3.3",
272 | "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
273 | "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
274 | },
275 | "path-to-regexp": {
276 | "version": "0.1.7",
277 | "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
278 | "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
279 | },
280 | "process-nextick-args": {
281 | "version": "2.0.1",
282 | "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
283 | "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
284 | },
285 | "proxy-addr": {
286 | "version": "2.0.6",
287 | "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.6.tgz",
288 | "integrity": "sha512-dh/frvCBVmSsDYzw6n926jv974gddhkFPfiN8hPOi30Wax25QZyZEGveluCgliBnqmuM+UJmBErbAUFIoDbjOw==",
289 | "requires": {
290 | "forwarded": "~0.1.2",
291 | "ipaddr.js": "1.9.1"
292 | }
293 | },
294 | "qs": {
295 | "version": "6.7.0",
296 | "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz",
297 | "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ=="
298 | },
299 | "range-parser": {
300 | "version": "1.2.1",
301 | "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
302 | "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="
303 | },
304 | "raw-body": {
305 | "version": "2.4.0",
306 | "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz",
307 | "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==",
308 | "requires": {
309 | "bytes": "3.1.0",
310 | "http-errors": "1.7.2",
311 | "iconv-lite": "0.4.24",
312 | "unpipe": "1.0.0"
313 | }
314 | },
315 | "readable-stream": {
316 | "version": "2.3.7",
317 | "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
318 | "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
319 | "requires": {
320 | "core-util-is": "~1.0.0",
321 | "inherits": "~2.0.3",
322 | "isarray": "~1.0.0",
323 | "process-nextick-args": "~2.0.0",
324 | "safe-buffer": "~5.1.1",
325 | "string_decoder": "~1.1.1",
326 | "util-deprecate": "~1.0.1"
327 | }
328 | },
329 | "safe-buffer": {
330 | "version": "5.1.2",
331 | "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
332 | "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
333 | },
334 | "safer-buffer": {
335 | "version": "2.1.2",
336 | "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
337 | "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
338 | },
339 | "send": {
340 | "version": "0.17.1",
341 | "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz",
342 | "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==",
343 | "requires": {
344 | "debug": "2.6.9",
345 | "depd": "~1.1.2",
346 | "destroy": "~1.0.4",
347 | "encodeurl": "~1.0.2",
348 | "escape-html": "~1.0.3",
349 | "etag": "~1.8.1",
350 | "fresh": "0.5.2",
351 | "http-errors": "~1.7.2",
352 | "mime": "1.6.0",
353 | "ms": "2.1.1",
354 | "on-finished": "~2.3.0",
355 | "range-parser": "~1.2.1",
356 | "statuses": "~1.5.0"
357 | },
358 | "dependencies": {
359 | "ms": {
360 | "version": "2.1.1",
361 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
362 | "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg=="
363 | }
364 | }
365 | },
366 | "serve-static": {
367 | "version": "1.14.1",
368 | "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz",
369 | "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==",
370 | "requires": {
371 | "encodeurl": "~1.0.2",
372 | "escape-html": "~1.0.3",
373 | "parseurl": "~1.3.3",
374 | "send": "0.17.1"
375 | }
376 | },
377 | "setprototypeof": {
378 | "version": "1.1.1",
379 | "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
380 | "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw=="
381 | },
382 | "sqlstring": {
383 | "version": "2.3.1",
384 | "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
385 | "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A="
386 | },
387 | "statuses": {
388 | "version": "1.5.0",
389 | "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
390 | "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
391 | },
392 | "string_decoder": {
393 | "version": "1.1.1",
394 | "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
395 | "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
396 | "requires": {
397 | "safe-buffer": "~5.1.0"
398 | }
399 | },
400 | "toidentifier": {
401 | "version": "1.0.0",
402 | "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
403 | "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw=="
404 | },
405 | "type-is": {
406 | "version": "1.6.18",
407 | "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
408 | "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
409 | "requires": {
410 | "media-typer": "0.3.0",
411 | "mime-types": "~2.1.24"
412 | }
413 | },
414 | "unpipe": {
415 | "version": "1.0.0",
416 | "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
417 | "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw="
418 | },
419 | "util-deprecate": {
420 | "version": "1.0.2",
421 | "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
422 | "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
423 | },
424 | "utils-merge": {
425 | "version": "1.0.1",
426 | "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
427 | "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM="
428 | },
429 | "vary": {
430 | "version": "1.1.2",
431 | "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
432 | "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
433 | }
434 | }
435 | }
436 |
--------------------------------------------------------------------------------
/nodejs-basics/path.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Path Module
3 | *
4 | * The path module provides utilities for working with file and directory paths.
5 | *
6 | */
7 | const path = require('path');
8 |
9 |
10 | // Normalization
11 | console.log('normalization : ' + path.normalize('/nodejs-basics/nodejs//node/dir/tab/..'));
12 |
13 | // Join
14 | console.log('joint path : ' + path.join('/nodejs-basics', 'nodejs', 'node/dir', 'tab', '..'));
15 |
16 | // Resolve
17 | console.log('resolve : ' + path.resolve('path_example.js'));
18 |
19 | // Extension
20 | console.log('ext name: ' + path.extname('path_example.js'));
--------------------------------------------------------------------------------
/nodejs-basics/play-video.js:
--------------------------------------------------------------------------------
1 | /**
2 | * -------------------------
3 | * Play video using Node
4 | * -------------------------
5 | *
6 | * RUN: cmd > node play-video.js
7 | *
8 | * */
9 | const http = require('http');
10 | const fs = require('fs'); // to help serve a local video file
11 |
12 | // Create an instance of the http server to handle HTTP requests
13 | let app = http.createServer((req, res) => {
14 | // Set a response type of mp4 video for the response
15 | res.writeHead(200, { 'Content-Type': 'video/mp4' });
16 |
17 | // Read the video into a stream
18 | let vidstream = fs.createReadStream('assets/NASA.mp4');
19 |
20 | // Pipe our stream into the response
21 | vidstream.pipe(res);
22 | });
23 |
24 | // Start the server on port 3000
25 | app.listen(3000, '127.0.0.1');
26 | console.log('Node server running on port 3000');
27 |
--------------------------------------------------------------------------------
/nodejs-basics/process.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Process Object
3 | *
4 | * The process is a global object, an instance of EventEmitter, can be accessed from anywhere.
5 | *
6 | * It provides the facility to get process information such as process id, architecture, platform,
7 | * version, release, uptime, upu usage etc. It can also be used to kill process, set uid, set groups, unmask etc.
8 | *
9 | */
10 |
11 |
12 | // Returns process architecture: 'arm', 'ia32', or 'x64'
13 | console.log(`Process Architecture: ${process.arch}`);
14 |
15 |
16 |
17 | // Returns process id of the process
18 | console.log(`Process PID: ${process.pid}`);
19 |
20 |
21 |
22 | // Returns platform of the process: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
23 | console.log(`Process Platform: ${process.platform}`);
24 |
25 |
26 |
27 | // Returns the node version
28 | console.log(`Process Version: ${process.version}`);
29 |
30 |
31 |
32 | // Returns path of current working directory
33 | console.log(`Current directory: ${process.cwd()}`);
34 |
35 |
36 |
37 | // Returns the Node.js process uptime in seconds.
38 | console.log(`Uptime: ${process.uptime()}`);
39 |
40 |
41 |
42 | // Returns an object having information of memory usage.
43 | console.log(`Memory Usage: ${JSON.stringify(process.memoryUsage())}`);
44 |
45 |
46 |
47 | // Print command line arguments
48 | process.argv.forEach((value, index, array) => {
49 | console.log(`${index}: ${value}`);
50 | });
51 |
--------------------------------------------------------------------------------
/nodejs-basics/querystring.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Query-String
3 | *
4 | * The Node.js Query String provides methods to deal with query string.
5 | * It can be used to convert query string into JSON object and vice-versa.
6 | *
7 | */
8 |
9 |
10 | /**
11 | * Query-String parse()
12 | *
13 | */
14 | querystring = require('querystring');
15 | const obj = querystring.parse('name=Pradeep&address=India');
16 | console.log(obj);
17 | // Output:
18 | // [Object: null prototype] { name: 'Pradeep', address: 'India' }
19 |
20 |
21 |
22 |
23 | /**
24 | * Query-String stringify()
25 | *
26 | */
27 | querystring = require('querystring');
28 | const qs = querystring.stringify({name:'Pradeep',address:'India'});
29 | console.log(qs);
30 | // Output
31 | // name=Pradeep&address=India
32 |
--------------------------------------------------------------------------------
/nodejs-basics/server.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Create a server in NodeJS
3 | */
4 | var http = require("http");
5 |
6 | http.createServer(function (request, response) {
7 | // Send the HTTP header
8 | // HTTP Status: 200 : OK
9 | // Content Type: text/plain
10 | response.writeHead(200, {'Content-Type': 'text/plain'});
11 | // Send the response body as "Hello World"
12 | response.end('Hello World\n');
13 | }).listen(4200);
14 | // Console will print the message
15 | console.log('Server running at http://localhost:4200/');
--------------------------------------------------------------------------------
/nodejs-basics/standard-input-output.js:
--------------------------------------------------------------------------------
1 | // Example: stdout()
2 | process.stdout.write('Hello World\n');
3 |
4 |
5 | // Example: 02
6 | let answers = [];
7 | let questions = [
8 | 'What is your name?',
9 | 'What is your fav hobby?',
10 | 'What is your preferred programming language?'
11 | ];
12 |
13 | function ask(i) {
14 | process.stdout.write(`\n ${questions[i]}`);
15 | process.stdout.write(' > ');
16 | }
17 |
18 | process.stdin.on('data', function(data) {
19 | answers.push(data.toString().trim());
20 |
21 | if (answers.length < questions.length) {
22 | ask(answers.length);
23 | } else {
24 | process.exit();
25 | }
26 | });
27 |
28 | ask(0); //function call
29 | process.on('exit', function() {
30 | process.stdout.write('\n\n');
31 | process.stdout.write(
32 | `Go ${answers[1]} ${answers[0]} you can finish writing ${answers[2]} later`
33 | );
34 | process.stdout.write('\n\n');
35 | });
--------------------------------------------------------------------------------
/nodejs-basics/stream.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Stream Module
3 | *
4 | * Streams are the objects that facilitate you to read data from a source
5 | * and write data to a destination. There are four types of streams in Node.js
6 | *
7 | * 1. Readable: This stream is used for read operations.
8 | * 2. Writable: This stream is used for write operations.
9 | * 3. Duplex: This stream can be used for both read and write operations.
10 | * 4. Transform: It is type of duplex stream where the output is computed according to input.
11 | *
12 | *
13 | * Each type of stream is an Event emitter instance and throws several events at different times.
14 | * Following are some commonly used events:
15 | *
16 | * 1. Data:This event is fired when there is data available to read.
17 | * 2. End:This event is fired when there is no more data available to read.
18 | * 3. Error: This event is fired when there is any error receiving or writing data.
19 | * 4. Finish:This event is fired when all data has been flushed to underlying system.
20 | *
21 | */
22 |
23 |
24 | /**
25 | * Reading from stream
26 | *
27 | */
28 | var fs = require("fs");
29 | var data = '';
30 |
31 | // Create a readable stream
32 | var readerStream = fs.createReadStream('input.txt');
33 |
34 | // Set the encoding to be utf8.
35 | readerStream.setEncoding('UTF8');
36 |
37 | // Handle stream events --> data, end, and error
38 | readerStream.on('data', function(chunk) {
39 | data += chunk;
40 | });
41 | readerStream.on('end',function(){
42 | console.log(data);
43 | });
44 | readerStream.on('error', function(err){
45 | console.log(err.stack);
46 | });
47 | console.log("Program Ended!");
48 |
49 |
50 |
51 | /**
52 | * Writing to stream
53 | *
54 | */
55 | var fs = require("fs");
56 | var data = 'A Solution of all Technology';
57 | // Create a writable stream
58 | var writerStream = fs.createWriteStream('output.txt');
59 |
60 | // Write the data to stream with encoding to be utf8
61 | writerStream.write(data,'UTF8');
62 |
63 | // Mark the end of file
64 | writerStream.end();
65 |
66 | // Handle stream events --> finish, and error
67 | writerStream.on('finish', function() {
68 | console.log("Write completed.");
69 | });
70 | writerStream.on('error', function(err){
71 | console.log(err.stack);
72 | });
73 | console.log("Program Ended!");
74 |
75 |
76 |
77 | /**
78 | * Piping Streams
79 | *
80 | * Piping is a mechanism where output of one stream is used as input to another stream.
81 | * There is no limit on piping operation.
82 | *
83 | */
84 | var fs = require("fs");
85 | // Create a readable stream
86 | var readerStream = fs.createReadStream('input.txt');
87 | // Create a writable stream
88 | var writerStream = fs.createWriteStream('output.txt');
89 | // Pipe the read and write operations
90 | // read input.txt and write data to output.txt
91 | readerStream.pipe(writerStream);
92 | console.log("Program Ended!");
93 |
94 |
95 |
96 |
97 | /**
98 | * Chaining Streams
99 | *
100 | * Chaining stream is a mechanism of creating a chain of multiple stream operations by
101 | * connecting output of one stream to another stream. It is generally used with piping operation.
102 | *
103 | */
104 | var fs = require("fs");
105 | var zlib = require('zlib');
106 | // Compress the file input.txt to input.txt.gz
107 | fs.createReadStream('input.txt')
108 | .pipe(zlib.createGzip())
109 | .pipe(fs.createWriteStream('input.txt.gz'));
110 | console.log("File Compressed.");
111 |
--------------------------------------------------------------------------------
/nodejs-basics/string-decoder.js:
--------------------------------------------------------------------------------
1 | /**
2 | * String Decoder
3 | *
4 | * The Node.js StringDecoder is used to decode buffer into string.
5 | * It is similar to buffer.toString() but provides extra support to UTF.
6 | *
7 | */
8 |
9 | const { StringDecoder } = require('string_decoder');
10 | const decoder = new StringDecoder('utf8');
11 |
12 |
13 | const rupee = Buffer.from([0xE2, 0x82, 0xB9]);
14 | console.log(decoder.write(rupee)); // ₹
15 |
16 |
17 | const euro = Buffer.from([0xE2, 0x82, 0xAC]);
18 | console.log(decoder.write(euro)); // €
19 |
--------------------------------------------------------------------------------
/nodejs-basics/timmer.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Timer Module
3 | *
4 | */
5 |
6 | // Example: setInterval()
7 | setInterval(function() {
8 | // console.log("setInterval: 1 millisecond completed...");
9 | }, 1000);
10 |
11 |
12 |
13 | // Example: setTimeout()
14 | var recursive = function () {
15 | //console.log("Hey! 1000 millisecond completed!..");
16 | setTimeout(recursive, 1000);
17 | }
18 | recursive();
19 |
20 |
21 | // Example: setInterval(), setTimeout() and clearInterval()
22 | function welcome () {
23 | console.log("Welcome to JavaTpoint!");
24 | }
25 | var id1 = setTimeout(welcome, 1010);
26 | var id2 = setInterval(welcome, 1000);
27 | //clearTimeout(id1);
28 | clearInterval(id2);
--------------------------------------------------------------------------------
/nodejs-basics/tls.js:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Transport Layer Security (TLS)
4 | *
5 | * It is the successor to Secure Sockets Layer (SSL). TLS along with SSL is
6 | * used for cryptographic protocols to secure communication over the web.
7 | *
8 | * TLS uses public-key cryptography to encrypt messages. It encrypts
9 | * communication generally on the TCP layer.
10 | *
11 | */
12 |
13 | const tls = require('tls');
14 |
15 | function connected(stream) {
16 | if (stream) {
17 | // socket connected
18 | stream.write("GET / HTTP/1.0\n\rHost: encrypted.google.com:443\n\r\n\r");
19 | } else {
20 | console.log("Connection failed!");
21 | }
22 | }
23 | // needed to keep socket variable in scope
24 | var dummy = this;
25 | // try to connect to the server
26 | dummy.socket = tls.connect(443, 'encrypted.google.com', function() {
27 | // callback called only after successful socket connection
28 | dummy.connected = true;
29 | if (dummy.socket.authorized) {
30 | // authorization successful
31 | dummy.socket.setEncoding('utf-8');
32 | connected(dummy.socket);
33 | } else {
34 | // authorization failed
35 | console.log(dummy.socket.authorizationError);
36 | connected(null);
37 | }
38 | });
39 | dummy.socket.addListener('data', function(data) {
40 | // received data
41 | console.log(data);
42 | });
43 | dummy.socket.addListener('error', function(error) {
44 | if (!dummy.connected) {
45 | // socket was not connected, notify callback
46 | connected(null);
47 | }
48 | console.log("FAIL");
49 | console.log(error);
50 | });
51 | dummy.socket.addListener('close', function() {
52 | console.log('Connection Closed!');
53 | });
54 |
--------------------------------------------------------------------------------
/nodejs-basics/v8.js:
--------------------------------------------------------------------------------
1 | /**
2 | * V8 Engine
3 | *
4 | * V8 is an open source JavaScript engine developed by the Chromium project
5 | * for the Google Chrome web browser. It is written in C++.
6 | *
7 | * It is used in many projects such as Couchbase, MongoDB and Node.js.
8 | *
9 | **/
10 |
11 | //---------------------------
12 | // v8.getHeapStatistics()
13 | //---------------------------
14 | var v8 = require('v8');
15 | console.log(v8.getHeapStatistics());
16 | // Output
17 | /**
18 | {
19 | total_heap_size: 6537216,
20 | total_heap_size_executable: 1048576,
21 | total_physical_size: 6537216,
22 | total_available_size: 1520712208,
23 | used_heap_size: 4204768,
24 | heap_size_limit: 1526909922,
25 | malloced_memory: 8192,
26 | peak_malloced_memory: 406408,
27 | does_zap_garbage: 0
28 | }
29 | */
30 |
31 |
32 |
33 |
34 | //-----------------------------
35 | // v8.getHeapSpaceStatistics()
36 | //-----------------------------
37 | var v8 = require('v8');
38 | console.log(v8.getHeapSpaceStatistics());
39 | // Output
40 | /**
41 | [
42 | { space_name: 'read_only_space',
43 | space_size: 524288,
44 | space_used_size: 35208,
45 | space_available_size: 480376,
46 | physical_space_size: 524288 },
47 | { space_name: 'new_space',
48 | space_size: 2097152,
49 | space_used_size: 980952,
50 | space_available_size: 50216,
51 | physical_space_size: 2097152 },
52 | { space_name: 'old_space',
53 | space_size: 2330624,
54 | space_used_size: 2272568,
55 | space_available_size: 184,
56 | physical_space_size: 2330624 },
57 | { space_name: 'code_space',
58 | space_size: 1048576,
59 | space_used_size: 571968,
60 | space_available_size: 0,
61 | physical_space_size: 1048576 },
62 | { space_name: 'map_space',
63 | space_size: 536576,
64 | space_used_size: 344784,
65 | space_available_size: 0,
66 | physical_space_size: 536576 },
67 | { space_name: 'large_object_space',
68 | space_size: 0,
69 | space_used_size: 0,
70 | space_available_size: 1520180736,
71 | physical_space_size: 0
72 | }
73 | ]
74 | */
--------------------------------------------------------------------------------
/nodejs-basics/web-module.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Web Module
3 | *
4 | * Web Server is a software program that handles HTTTP requests sent by HTTP clients
5 | * like web browsers, and returns web pages in response to the clients. Web servers
6 | * usually respond with html documents along with images, style sheets and scripts.
7 | *
8 | *
9 | * ------------------------------
10 | * Web Application Architecture
11 | * ------------------------------
12 | *
13 | * 1. Client Layer: The Client layer contains web browsers, mobile browsers or applications
14 | * which can make HTTP request to the web server.
15 | *
16 | * 2. Server Layer: The Server layer contains Web server which can intercepts the request made
17 | * by clients and pass them the response.
18 | *
19 | * 3. Business Layer: The business layer contains application server which is utilized by web
20 | * server to do required processing. This layer interacts with data layer via data base or some external programs.
21 | *
22 | * 4. Data Layer: The Data layer contains databases or any source of data.
23 | *
24 | */
25 |
26 |
27 | var http = require('http');
28 | var fs = require('fs');
29 | var url = require('url');
30 |
31 | // Create a server
32 | http.createServer( function (request, response) {
33 | // Parse the request containing file name
34 | var pathname = url.parse(request.url).pathname;
35 |
36 | // Print the name of the file for which request is made.
37 | console.log("Request for " + pathname + " received.");
38 |
39 | // Read the requested file content from file system
40 | fs.readFile(pathname.substr(1), function (err, data) {
41 | if (err) {
42 | console.log(err);
43 | // HTTP Status: 404 : NOT FOUND
44 | // Content Type: text/plain
45 | response.writeHead(404, {'Content-Type': 'text/html'});
46 | }else{
47 | //Page found
48 | // HTTP Status: 200 : OK
49 | // Content Type: text/plain
50 | response.writeHead(200, {'Content-Type': 'text/html'});
51 |
52 | // Write the content of the file to response body
53 | response.write(data.toString());
54 | }
55 | // Send the response body
56 | response.end();
57 | });
58 | }).listen(4200);
59 | // Console will print the message
60 | console.log('Server running at http://localhost:4200/index.html');
61 |
--------------------------------------------------------------------------------
/nodejs-basics/zlib.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Zlib Module
3 | *
4 | * The Node.js Zlib module is used to provide compression and decompression (zip and unzip)
5 | * functionalities. It is implemented using Gzip and deflate/inflate.
6 | *
7 | */
8 |
9 |
10 | // --------------------------------------------------------------------
11 | // Method Description
12 | // --------------------------------------------------------------------
13 | // constants Returns an object containing Zlib constants
14 | // createDeflate() Creates a Deflate object
15 | // createDeflateRaw() Creates a DeflateRaw object
16 | // createGunzip() Creates a Gunzip object
17 | // createGzip() Creates a Gzip object
18 | // createInflate() Creates a Inflate object
19 | // createInflateRaw() Creates a InflateRaw object
20 | // createUnzip() Creates a Unzip object
21 | // deflate() Compress a string or buffer, using Deflate
22 | // deflateSync() Compress a string or buffer, syncronously, using Deflate
23 | // deflateRaw() Compress a string or buffer, using DeflateRaw
24 | // deflateRawSync() Compress a string or buffer, syncronously, using DeflateRaw
25 | // gunzip() Compress a string or buffer, using Gunzip
26 | // gunzipSync() Compress a string or buffer, syncronously, using Gunzip
27 | // gzip() Compress a string or buffer, using Gzip
28 | // gzipSync() Compress a string or buffer, syncronously, using Gzip
29 | // inflate() Decompress a string or buffer, using Inflate
30 | // inflateSync() Decompress a string or buffer, syncronously, using Inflate
31 | // inflateRaw() Decompress a string or buffer, using InflateRaw
32 | // inflateRawSync() Decompress a string or buffer, syncronously, using InflateRaw
33 | // unzip() Decompress a string or buffer, using Unzip
34 | // unzipSync() Decompress a string or buffer, syncronously, using Unzip
35 |
36 |
37 |
38 | //--------------------------
39 | // Example: Compress File
40 | //--------------------------
41 |
42 | var zlib = require('zlib');
43 | var fs = require('fs');
44 | var gzip = zlib.createGzip();
45 | var r = fs.createReadStream('input.txt');
46 | var w = fs.createWriteStream('input.txt.gz');
47 | r.pipe(gzip).pipe(w);
48 |
--------------------------------------------------------------------------------
/nodejs-commands.md:
--------------------------------------------------------------------------------
1 | ## NodeJS Commands
2 |
3 | |Sl.No.| Commands | Description |
4 | |------|----------------------------|-------------------------------|
5 | | 01. |npm install node@14.8.0 | Install node specific version |
6 | | 02. |npm init | Creates package.json |
7 | | 03. |npm install | Install the dependencies in the local node_modules folder |
8 | | 04. |bower install | package manager |
9 | | 05. |npm install -g gulp | |
10 | | 06. |npm install -g bower | |
11 | | 07. |npm install -g live-server | |
12 | | 08. |npm install -g grunt-cli | |
13 | | 09. |live-server | Start NodeJs Server |
14 | | 10. |npm install -S express | |
15 | | 11. |npm install -S body-parser | |
16 | | 12. |npm start | |
17 | | 13. |gulp develop | Server Start |
18 | | 14. |gulp help | gulp Help |
19 | | 15. |gulp build | Clean and minification into single file |
20 | | 16. |gulp serve | |
21 | | 17. |gulp watch | |
22 | | 18. |gulp test:tdd | Unit Testing |
23 | | 19. |gem install sass | |
24 | | 20. |sass -? | Help |
25 | | 21. |sass --update var_styles.scss| |
26 | | 22. |sass --watch dir:dir | Watch for changes |
27 | | 23. |npm install -g webpack | Istall webpack globally |
28 | | 24. |webpack | Run |
29 | | 25. |npm -l | Display full usage info |
30 | | 26. |ruby -v | Ruby Version |
31 | | 27. |node -v | Node Version |
32 | | 28. |npm -v | Node Package Manager Version |
33 | | 29. |tsc -v | TypeScript Version |
34 | | 30. |git version | Git Version |
35 | | 31. |webpack -v | Webpack Version |
36 | | 32. |npm install mongoose | |
37 | | 33. |npm config rm proxy | |
38 | | 34. |npm config rm https-proxy | |
39 | | 35. |npm config list | |
40 | | 36. |npm install firebase angularfire2 --save |
41 | | 37. |npm install git+https://github.com/angular/angularfire2.git|
42 | | 38. |npm install firebase angularfire2@next --save |
43 | | 39. |npm uninstall -g angular-cli | |
44 | | 40. |npm cache clean | |
45 | | 41. |npm install -g typescript | |
46 | | 42. |npm install --save rxjs@5.5.2| Reactive Extensions Library for JavaScript |
47 | | 43. |npm install express-session | |
48 | | 44. |node app | Run app.js file on node server |
49 | | 45. |npm install -g jshint | |
50 | | 46. |npm install express --save | Install express into local project |
51 | | 47. |npm install cors --save | Cross Origin Resource Sharing --> It allows open api to accessibale by other domains |
52 | | 48. |npm install body-parser --save | |
53 | | 49. |npm install underscore --save | |
54 | | 50. |npm remove underscore --save | |
55 | | 51. |npm install ws --save | Install WebSocket |
56 | | 52. |npm install socket.io --save | Used for creating websocket when browser doestn't support websocket |
57 | | 53. |npm install -g mocha | JavaScript Unit Testing framework |
58 | | 54. |mocha | To run mocha test |
59 | | 55. |npm install nock --save-dev | Use to create mock server for testing |
60 | | 56. |npm install rewire --save-dev | Use for Injecting dependencies |
61 | | 57. |npm install sinon --save-dev | Use to create mock object for test |
62 | | 58. |npm install -g istanbul | JavaScript test coverage tool |
63 | | 59. |istanbul cover _mocha | Run istanbul report |
64 | | 60. |npm install supertest --save-dev| |
65 | | 61. |npm install cheerio --save-dev | |
66 | | 62. |npm install grunt-contib-jshint --save-dev|
67 | | 63. |npm install grunt-contrib-less --save-dev|
68 | | 64. |grunt css | Convert ".less" file into corresponding ".css" files |
69 | | 65. |npm install grunt-autoprefixer --save-dev| Add code for browser dependencies in css |
70 | | 66. |npm install grunt-browserify --save-dev | Create bundle.js combining all files together |
71 | | 67. |npm install grunt-contrib-watch --save-dev| |
72 | | 68. |grunt watch | |
73 | | 69. |ng add @angular/material | |
74 | | 70. |npm install -g live-server | |
75 | | 71. |npm link | create a symlink in the global folder |
76 | | 72. |npm link redis | link-install the package |
77 |
--------------------------------------------------------------------------------
/nodejs-mysql/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 |
8 | # dependencies
9 | /node_modules
10 |
11 | # profiling files
12 | chrome-profiler-events.json
13 | speed-measure-plugin.json
14 |
15 | # IDEs and editors
16 | /.idea
17 | .project
18 | .classpath
19 | .c9/
20 | *.launch
21 | .settings/
22 | *.sublime-workspace
23 |
24 | # IDE - VSCode
25 | .vscode/*
26 | !.vscode/settings.json
27 | !.vscode/tasks.json
28 | !.vscode/launch.json
29 | !.vscode/extensions.json
30 |
31 | # misc
32 | /.sass-cache
33 | /connect.lock
34 | /coverage
35 | /libpeerconnection.log
36 | npm-debug.log
37 | yarn-error.log
38 | testem.log
39 | /typings
40 |
41 | # System Files
42 | .DS_Store
43 | Thumbs.db
44 |
--------------------------------------------------------------------------------
/nodejs-mysql/alter-table.js:
--------------------------------------------------------------------------------
1 | let db_pool = require('./config').mysql_connect;
2 |
3 | let sql = `ALTER TABLE employee ADD COLUMN salary DOUBLE(10, 2)`;
4 |
5 | // connect to the MySQL server
6 | db_pool.getConnection((err) => {
7 | if (err) throw err;
8 | console.log("Connected!");
9 |
10 | // execute the SQL QUery
11 | db_pool.query(sql, (err, result) => {
12 | if (err) throw err;
13 |
14 | console.log("Table altered!");
15 | });
16 | });
17 |
--------------------------------------------------------------------------------
/nodejs-mysql/config.js:
--------------------------------------------------------------------------------
1 | /**
2 | * CONNECTION POOL
3 | *
4 | */
5 | var mysql = require('mysql');
6 |
7 | config = {
8 | mysql_connect : mysql.createPool({
9 | connectionLimit: 10,
10 | host: "localhost",
11 | user: "root",
12 | password: "root",
13 | database: "learning_zone"
14 | })
15 | };
16 | module.exports = config;
17 |
--------------------------------------------------------------------------------
/nodejs-mysql/create-db.js:
--------------------------------------------------------------------------------
1 | var mysql = require('mysql');
2 |
3 | var con = mysql.createConnection({
4 | host: "localhost",
5 | user: "root",
6 | password: "root"
7 | });
8 |
9 | con.connect(function(err) {
10 | if (err) throw err;
11 | console.log("Connected!");
12 | con.query("CREATE DATABASE learning_zone", function (err, result) {
13 | if (err) throw err;
14 | console.log("Database created");
15 | });
16 | });
--------------------------------------------------------------------------------
/nodejs-mysql/create-table.js:
--------------------------------------------------------------------------------
1 | let db_pool = require('./config').mysql_connect;
2 |
3 | // connect to the MySQL server
4 | db_pool.getConnection((err) => {
5 | if (err) throw err;
6 | console.log("Connected!");
7 |
8 | let statement = `create table if not exists employee(
9 | id int primary key auto_increment,
10 | name varchar(255) not null,
11 | age INT(3),
12 | city VARCHAR(255),
13 | active tinyint(1) not null default 0
14 | )`;
15 |
16 |
17 | db_pool.query(statement, (err, result) => {
18 | if (err) throw err;
19 | console.log("Table created!");
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/nodejs-mysql/delete-record.js:
--------------------------------------------------------------------------------
1 | let db_pool = require('./config').mysql_connect;
2 |
3 | // Avoid SQL injection
4 | let sql = `DELETE FROM employee WHERE id = ?`;
5 |
6 | // connect to the MySQL server
7 | db_pool.getConnection((err) => {
8 | if (err) throw err;
9 |
10 | // execute the SQL QUery
11 | db_pool.query(sql, [20], (err, result) => {
12 | if (err) throw err;
13 |
14 | console.log("Number of records deleted: " + result.affectedRows);
15 | });
16 | });
17 |
--------------------------------------------------------------------------------
/nodejs-mysql/insert-record.js:
--------------------------------------------------------------------------------
1 | let db_pool = require('./config').mysql_connect;
2 |
3 |
4 | // connect to the MySQL server
5 | db_pool.getConnection(function(err) {
6 | if (err) throw err;
7 | console.log("Connected!");
8 |
9 | // insert statment
10 | let stmt = "INSERT INTO employee (name, age, city) VALUES ?";
11 | let values = [
12 | ['Bharat Kumar', '25', 'Mumbai'],
13 | ['John Cena', '35', 'Las Vegas'],
14 | ['Ryan Cook', '15', 'CA']
15 | ];
16 |
17 | // execute the insert statment
18 | db_pool.query(stmt, [values], function (err, result) {
19 | if (err) {
20 | return console.error(err.message);
21 | }
22 |
23 | // get total records
24 | console.log("Number of records inserted: " + result.affectedRows);
25 | });
26 | });
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/nodejs-mysql/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "requires": true,
3 | "lockfileVersion": 1,
4 | "dependencies": {
5 | "bignumber.js": {
6 | "version": "9.0.0",
7 | "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
8 | "integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A=="
9 | },
10 | "core-util-is": {
11 | "version": "1.0.2",
12 | "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
13 | "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
14 | },
15 | "inherits": {
16 | "version": "2.0.4",
17 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
18 | "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
19 | },
20 | "isarray": {
21 | "version": "1.0.0",
22 | "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
23 | "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
24 | },
25 | "mysql": {
26 | "version": "2.18.1",
27 | "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz",
28 | "integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==",
29 | "requires": {
30 | "bignumber.js": "9.0.0",
31 | "readable-stream": "2.3.7",
32 | "safe-buffer": "5.1.2",
33 | "sqlstring": "2.3.1"
34 | }
35 | },
36 | "process-nextick-args": {
37 | "version": "2.0.1",
38 | "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
39 | "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
40 | },
41 | "readable-stream": {
42 | "version": "2.3.7",
43 | "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
44 | "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
45 | "requires": {
46 | "core-util-is": "~1.0.0",
47 | "inherits": "~2.0.3",
48 | "isarray": "~1.0.0",
49 | "process-nextick-args": "~2.0.0",
50 | "safe-buffer": "~5.1.1",
51 | "string_decoder": "~1.1.1",
52 | "util-deprecate": "~1.0.1"
53 | }
54 | },
55 | "safe-buffer": {
56 | "version": "5.1.2",
57 | "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
58 | "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
59 | },
60 | "sqlstring": {
61 | "version": "2.3.1",
62 | "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
63 | "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A="
64 | },
65 | "string_decoder": {
66 | "version": "1.1.1",
67 | "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
68 | "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
69 | "requires": {
70 | "safe-buffer": "~5.1.0"
71 | }
72 | },
73 | "util-deprecate": {
74 | "version": "1.0.2",
75 | "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
76 | "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/nodejs-mysql/select-record.js:
--------------------------------------------------------------------------------
1 | let db_pool = require('./config').mysql_connect;
2 |
3 |
4 | let stmt = `SELECT * FROM employee`;
5 | db_pool.getConnection((error) => {
6 | if (error) {
7 | return console.error('Connection Error: '+error.message);
8 | }
9 |
10 | // execute the SELECT Statment
11 | db_pool.query(stmt, (err, result) => {
12 | if (err) {
13 | return console.error('Table Error: '+err.message);
14 | }
15 |
16 | // Display records
17 | console.log(result);
18 | });
19 | });
20 |
--------------------------------------------------------------------------------
/nodejs-mysql/update-record.js:
--------------------------------------------------------------------------------
1 | let db_pool = require('./config').mysql_connect;
2 |
3 | let sql = `UPDATE employee
4 | SET city = ?
5 | WHERE id = ?`;
6 |
7 | let data = ['Bangalore', 5];
8 |
9 | // connect to the MySQL server
10 | db_pool.getConnection((err) => {
11 | if (err) throw err;
12 |
13 | // execute the UPDATE statement
14 | db_pool.query(sql, data, (error, result) => {
15 | if (error){
16 | return console.error(error.message);
17 | }
18 |
19 | console.log(result.affectedRows + " record(s) updated");
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/nodejs-programming.md:
--------------------------------------------------------------------------------
1 | # Node.js Coding Practice
2 |
3 |
4 |
5 | ## Q. What will happen when that code will be executed?
6 |
7 | ```js
8 | var EventEmitter = require("events");
9 |
10 | var eventObj = new EventEmitter();
11 |
12 | eventObj.on("event1", function () {
13 | console.log("Event1 fired!");
14 | process.nextTick(function () {
15 | eventObj.emit("event2");
16 | });
17 | });
18 |
19 | eventObj.on("event2", function () {
20 | console.log("Event2 fired!");
21 | process.nextTick(function () {
22 | eventObj.emit("event3");
23 | });
24 | });
25 |
26 | eventObj.on("event3", function () {
27 | console.log("Event3 fired!");
28 | process.nextTick(function () {
29 | eventObj.emit("event1");
30 | });
31 | });
32 |
33 | eventObj.emit("event1");
34 | ```
35 |
36 | Answer
37 |
38 | ```js
39 | Event1 fired!
40 | Event2 fired!
41 | Event3 fired!
42 | ...
43 | ...
44 | ...
45 | Event1 fired!
46 | Event2 fired!
47 | Event3 fired!
48 | ```
49 |
50 |
51 |
52 |
55 |
56 | ## Q. Rewrite the code sample without try/catch block
57 |
58 | ```js
59 | async function getData(req, res) {
60 | try {
61 | const a = await functionA();
62 | const b = await functionB();
63 | res.send("some result");
64 | } catch (error) {
65 | res.send(error.stack);
66 | }
67 | }
68 | ```
69 |
70 | Answer
71 |
72 | ```js
73 | async function getData() {
74 | const a = await functionA().catch((error) => console.log(error));
75 | const b = await functionB().catch((error) => console.log(error));
76 | if (a && b) {
77 | console.log("some result");
78 | }
79 | }
80 | ```
81 |
82 |
83 |
84 |
87 |
88 | ## Q. Consider following code snippet
89 |
90 | ```js
91 | {
92 | console.time("loop");
93 | for (var i = 0; i < 1000000; i += 1) {
94 | // Do nothing
95 | }
96 | console.timeEnd("loop");
97 | }
98 | ```
99 |
100 | The time required to run this code in Google Chrome is considerably more than the time required to run it in Node.js Explain why this is so, even though both use the v8 JavaScript Engine.
101 |
102 | Answer
103 |
104 | Within a web browser such as Chrome, declaring the variable `i` outside of any function\'s scope makes it global and therefore binds it as a property of the `window` object. As a result, running this code in a web browser requires repeatedly resolving the property `i` within the heavily populated `window` namespace in each iteration of the `for` loop.
105 |
106 | In Node.js, however, declaring any variable outside of any function\'s scope binds it only to the module\'s own scope (not the `window` object) which therefore makes it much easier and faster to resolve.
107 |
108 |
109 |
110 |
113 |
114 | ## Q. Rewrite promise-based Node.js applications to Async/Await
115 |
116 | ```js
117 | function asyncTask() {
118 | return functionA()
119 | .then((valueA) => functionB(valueA))
120 | .then((valueB) => functionC(valueB))
121 | .then((valueC) => functionD(valueC))
122 | .catch((err) => logger.error(err));
123 | }
124 | ```
125 |
126 | Answer
127 |
128 | ```js
129 | async function asyncTask() {
130 | try {
131 | const valueA = await functionA();
132 | const valueB = await functionB(valueA);
133 | const valueC = await functionC(valueB);
134 | return await functionD(valueC);
135 | } catch (err) {
136 | logger.error(err);
137 | }
138 | }
139 | ```
140 |
141 |
142 |
143 |
146 |
--------------------------------------------------------------------------------