Learning-NodeJS
Learning-NodeJS copied to clipboard
Mastering NodeJS :turtle:
References
Install Ubuntu
- https://snapcraft.io/node
- https://github.com/nodesource/distributions/blob/master/README.md#debinstall
Event Loop

https://github.com/AlexGalhardo/Learning-NodeJS/assets/19540357/32ac6d51-8ac6-48cc-a477-682602c9f683
- https://www.origamid.com/slide/javascript-completo-es6/#/0101-javascript-completo-es6/11
- Talk #27 - JavaScript Event Loop (Parte 1)
- Mas que diabos é o loop de eventos? | Philip Roberts | JSConf EU
- Javascript & Node.js: Do baixo ao alto nível
| Feature | Processo | Thread |
|---|---|---|
| Execução | Linha própria | Linha própria |
| Memória global (heap e data segmnent) | Própria | Compartilhada |
| Memória local (stack, registers, PCounter) | Sim | Geralmente |
| Consumo de memória | Normal | Ligeiramente menor |
| Manipuladores de recursos externos | Proprietário | Empresta do processo |
| Tempo de criação | Relativamente longo | Relativamente curto |
| Tempo de troca de contexto | Relativamente longo | Relativamente curto |
| Instâncias | Múltiplas | Múltiplas |
| Associação | Um programa (executável) | Um processo |
| Paralelismo | Limitado | Sim |
| Comunicação entre seus pares | Só com um mecanismo de IPC | Sim, dentro do processo |
| Eficiência de comunicação | Não | Sim |
| Comunicação direta com o OS | Sim | Não |
| Controle de exceções | Próprio | Próprio |
| Confiabilidade e segurança | Sim | Depende do código |
Articles
Commands
- $ npm init
- $ npm init -y
- $ npm start
- "scripts": { "start": "node index.js",
- $ npm run dev
- "scripts": { "dev": "nodemon index.js",
- Global Examples
- $ sudo npm install -g nodemon
- $ sudo npm install -g typescrypt
- $ sudo npm install -g ts-node
- $ sudo npm install -g express-generator
- $ sudo npm install -g lite-server
- Dependencies
- $ npm install mustache-express
- DevDependencies
- $ npm install --save-dev @types/node
- $ npm install --save-dev @types/mustache-express
- $ npm install --save-dev @types/validator
- $ npm install --save-dev @types/express
- $ npm i -D @types/body-parser
- -D = --save-dev
Latest Node Stable Version
- $ sudo npm cache clean -f
- $ sudo npm install -g n
- $ sudo n stable
- https://github.com/nvm-sh/nvm
NPM
- $ sudo npm install -g npm
Update all NPM packages
- $ npm i -g npm-check-updates
- $ ncu -u
YARN
- https://yarnpkg.com/getting-started/install
- $ sudo npm install -g yarn
Modules/Packages
- Pino Logging
- HTTP Requests
- HTTP Server
- https://expressjs.com/pt-br/
- https://www.npmjs.com/package/express-rate-limit
- https://express-validator.github.io/docs/
- https://www.npmjs.com/package/express-jwt
- https://www.npmjs.com/package/express-mysql-session
- https://www.npmjs.com/package/express-session
- https://expressjs.com/en/advanced/best-practice-performance.html
- Debug
- File System
- Async
- CORS
- Utilites
- Testing and Code Quality
- .gitginore
- CLI
- Validator
- Template Engine
- Cache
- Teste de Carga
- Parser URL Encoded
- Framework MVC
- Authentication
- Uploads
- Dates & Times
- EMAIL SMTP
- Slug
- .env
- Responses Compression
- SMS/WhatsAPP
- Browser
- ID
- Query String
- DataBases
- https://knexjs.org/
- https://devhints.io/knex
- https://sequelize.org/
- https://knexjs.org/
- JSON-SERVER
- Logs
- FAKE DATA
- REDIS
- VALIDATION
- DOCUMENTATION
TypeScrypt
- Links
- https://www.typescriptlang.org/
- https://www.typescriptlang.org/play
- https://stackblitz.com/edit/typescript-dh6svr?file=example%2Fsupermario.ts
- Comands
- $ sudo npm install -g tsc typescript ts-node
- $ npm install --save-dev @types/express @types/mustache-express @types/node copyfiles
- $ tsc --init
- $ tsc -w (ficar monitorando typescript)
- package.json
- "scripts":
- "start": "tsc ; nodemon ./dist/app",
- "scripts":
- tsconfig.json
- "outDir": "./dist",
- "rootDir": "./src",
- "module": "commonjs",
- "moduleResolution": "node"
Performance and Best Practices
- HTTP/2
- gRPC
- Cluster
- Errors Logging
- Hateoas
- Security HTTP Headers
- Loading Testing
SSL/HTTPS
- https://github.com/FiloSottile/mkcert
- https://letsencrypt.org/pt-br/
- https://certbot.eff.org/
- SegInfoBrasil - YouTube
Import/Export Modules
Older module.exports (ES5)
- Math.js
function sum(x, y) {
return x+y;
}
module.exports = sum;
- index.js
const Math = require('./Math');
console.log(`SUM: ${Math.sum(n1,n2)}`);
Modern Object (ES6+)
- Math.ts
function sum(x:number, y:number):number {
return x+y;
}
export default {
sum:sum, // sum
};
- index.ts
import * as Math from './Math';
console.log(`SUM: ${Math.sum(2,3)}`); // SUM: 5
Modern Functions (ES6+)
- Math.ts
export function sum(x:number, y:number):number {
return x+y;
}
- index.ts
import { sum } from './Math';
console.log(`SUM: ${sum(2,3)}`); // SUM: 5
JSON SERVER FAST REST API
- $ sudo npm install -g json-server
- Change PORT
- json-server --watch db.json --port 3004
- create db.json
{
"products": [
{
"id": 1,
"name": "Sushi",
"description": "A melhor comida que existe.",
"price": 8.5,
"category_id": 1
},
{
"id": 2,
"name": "Batata Frita",
"description": "Só o Cristiano Ronaldo não gosta.",
"price": 10.5,
"category_id": 1
},
{
"id": 3,
"name": "X-Tudo",
"description": "Melhor lanche que existe.",
"price": 12.5,
"category_id": 1
},
{
"id": 4,
"name": "Tubaina",
"description": "Os clássicos a gente nunca esquece.",
"price": 14.5,
"category_id": 2
},
{
"id": 5,
"name": "Koka Kola",
"description": "Refrigerante que faz mal.",
"price": 5.5,
"category_id": 2
},
{
"id": 6,
"name": "Dollynho",
"description": "Seu amiguinho, vamos brincar?",
"price": 7.5,
"category_id": 2
}
],
"categories": [
{
"id": 1,
"name": "Comida"
},
{
"id": 2,
"name": "Refrigerantes"
}
]
}
- $ json-server --watch db.json
| Request | URL | Details | headers: { 'Content-Type': 'application/json' } |
|---|---|---|---|
| GET | http://localhost:3000/products | Return all products | |
| GET | http://localhost:3000/products/1 | Return product by ID | |
| POST | http://localhost:3000/products | Create new product | { "nome": "Bolo de Cenoura com cobertura de chocolate", "descricao": "DELÍCIA", "preco": 9.5, "categoria_id": 1 } |
| PUT | http://localhost:3000/products/1 | Update all product data by ID | { "name": "Sushi edited", "description": "description edited", "preco": 10.5, "category_id": 1 } |
| PATCH | http://localhost:3000/products/1 | >Update some product data by ID | { "name": "New Sushi Name" } |
| DELETE | http://localhost:3000/products/1 | Delete a product by ID | |
| GET | http://localhost:3000/products?name=Sushi | Filter products by name | |
| GET | http://localhost:3000/products/?_page=1&_limit=2 | Get products by Pagination | |
| GET | http://localhost:3000/products/?_sort=nome&_order=desc | Get products order by |
Exampe with Node-Fetch
- $ npm install node-fetch
const fetch = require('node-fetch');
const API_URL = 'http://localhost:3000';
const ENDPOINT = 'products';
// --------- GET
fetch(`${API_URL}/${ENDPOINT}`, {
"method": "GET"
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));
// --------- POST
fetch(`${API_URL}/${ENDPOINT}`, {
method: 'POST',
body: JSON.stringify({
"name": "New item adicionado com NODEJS",
"description": "npm init e tals",
"price": 19.90,
"category_id": 1
}),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
// --------- PUT
const product_id_to_put = 8;
fetch(`${API_URL}/${ENDPOINT}/${product_id_to_put}`, {
method: 'PUT',
body: JSON.stringify({
"name": "PRODUTO 8 ATUALIZADO",
"description": "description atualized",
"price": 59.90,
"category_id": 2
}),
headers: { 'Content-Type': 'application/json' },
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));
// --------- PATCH
const product_id_to_patch = 12;
fetch(`${API_URL}/${ENDPOINT}/${product_id_to_patch}`, {
method: 'PATCH',
body: JSON.stringify({
"name": "Item 12 nome atualizado",
"price": 39.90,
}),
headers: { 'Content-Type': 'application/json' },
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));
// --------- DELETE
const product_id_to_delete = 3;
fetch(`${API_URL}/${ENDPOINT}/${product_id_to_delete}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));
// --------- FILTER BY NAME
const filterName = 'Sushi';
fetch(`${API_URL}/${ENDPOINT}?name=${filterName}`, {
"method": "GET"
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));
// ---------- ORDER BY
const ORDER = 'DESC';
const SORT = 'preco';
fetch(`${API_URL}/${ENDPOINT}/?_sort=${SORT}&_order=${ORDER}`, {
"method": "GET"
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));
// ----------- PAGINATION
let page = 3;
let limit = 4;
fetch(`${API_URL}/${ENDPOINT}/?_page=${page}&_limit=${limit}`, {
"method": "GET"
})
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error(err));