Beruflich Dokumente
Kultur Dokumente
Typescript y NodeJS
Crear directorio
1. npm init -y
2. tsc --init
Instalar dependencias:
Compilar:
tsc --watch
Ejecutar
node dist/index.js
Nota:
index.html
<html>
<head>
<title>Typescript + NodeJS</title>
</head>
<body>
<h1>Computadoras</h1>
<div>
<div id="contenedor"></div>
<button id="btn">Cargar</button>
</div>
<script>
const btn = document.querySelector("#btn");
const contenedor = document.getElementById("contenedor");
contenedor.addEventListener("dblclick",()=>{
contenedor.innerHTML = "";
});
btn.addEventListener("click", ()=>{
fetch('http://localhost:5000/computadoras')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
var resultado = "";
for(dato in myJson){
resultado +="<br/>Marca:
"+myJson[dato].marca;
resultado +="<br/>Modelo:
"+myJson[dato].modelo;
resultado +="<br/>Sistema:
"+myJson[dato].sistema;
resultado +="<br/>Ip:
"+myJson[dato].ip;
resultado +="<br/>Dns:
"+myJson[dato].dns+"<br/>";
}
contenedor.innerHTML = resultado;
});
});
</script>
</body>
</html>
index.ts
package.json
{
"name": "typescript-node01",
"version": "1.0.0",
"description": "Proyecto Typescript + Node JS",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies":{
"express": "^4.16.4"
},
"devDependencies": {
"@types/express": "^4.16.1"
}
}
servicio-component.ts
export interface ServicioComputadora{
marca:string
modelo:string
sistema:string
ip:string
dns:string
servidor.ts
import express from 'express'
import {Application} from 'express'
import {ServicioComputadora} from './servicio/servicio_computadora'
private saludar():void{
console.log("Iniciando el servidor...");
}
private setting():void{
this.app.set('port', this.port || process.env.PORT ||
5000)
}
//Promise
async listen(){
await this.app.listen(this.app.get('port'));
console.log("Servidor en http://localhost:5000");
//http://localhost:5000/saludo
this.app.get("/saludo",function(request,response){
response.send("<h1>Typescript + Node<font
color='red'>JS</font> </h1>");
});
//http://localhost:5000/computadoras
this.app.get("/computadoras",function(request,response){
var computadoras: ServicioComputadora[] = [{
marca:'DELL',
modelo:'1200',
sistema:'Windows Vista',
ip:'147.215.23.13',
dns:'8.8.8.8'},
{
marca:'DELL',
modelo:'Alienware',
sistema:'Windows 8.1',
ip:'147.215.23.16',
dns:'207.68.222.222'},
{
marca:'iMac Pro',
modelo:'AirBook Pro',
sistema:'OSX Solaris',
ip:'147.215.23.14',
dns:'207.68.222.222'},
{
marca:'DELL',
modelo:'1500',
sistema:'Windows XP',
ip:'147.215.23.11',
dns:'207.68.222.222'}];
response.send(computadoras);
});
tsconfing.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true
}
}