Como.o.event.loop.do.NodeJS.Funciona.mp4
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 |
- $ 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
Latest Node Stable Version
- $ sudo npm install -g npm
- $ npm i -g npm-check-updates
- $ ncu -u
- Pino Logging
- HTTP Requests
- HTTP Server
- Debug
- File System
- Async
- CORS
- Utilites
- Testing and Code Quality
- .gitginore
- PDF
- 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
- JSON-SERVER
- Logs
- FAKE DATA
- REDIS
- VALIDATION
- DOCUMENTATION
- Links
- 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",
- 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
Older module.exports (ES5)
function sum(x, y) {
return x+y;
}
module.exports = sum;
const Math = require('./Math');
console.log(`SUM: ${Math.sum(n1,n2)}`);
function sum(x:number, y:number):number {
return x+y;
}
export default {
sum:sum, // sum
};
import * as Math from './Math';
console.log(`SUM: ${Math.sum(2,3)}`); // SUM: 5
export function sum(x:number, y:number):number {
return x+y;
}
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 |
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));