Ejercicio chat

En el chat que ya tenemos vamos a incluir algunas mejoras:

– Evitar que se puedan mandar mensajes más largos de 140 caracteres
– Filtrar palabras malsonantes
– Posibilidad de enviar emoticonos
– Posibilidad de tener cuatro salas diferentes de chat y elegir a cual te quieres conectar.

Server

http.createServer(function (req, res) {

    let url = "";
    let type = "text/html";
    if (req.url.endsWith(".css")) {
        url = "." + req.url;
        type = "text/css";
    } else if (req.url.endsWith(".js")) {
        url = "." + req.url;
        type = "text/javascript";
    } else {
        url = "pages" + (req.url=="/"?"/index":req.url) + ".html";
    }
    console.log(url);
    fs.readFile(url, function (err, data) {
        if (!err) {
            res.writeHead(200, { "Content-Type": type });
            res.end(data);
        }
        else {
            res.writeHead(404, { "Content-Type": "text/html" });
            res.end("<h1>Not found</h1>");
        }
    });
}).listen(port);

Empezando con express

npm i express

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

The general syntax for a route is shown below

app.METHOD(PATH, HANDLER)
Wherein,

1) app is an instance of the express module

2) METHOD is an HTTP request method (GET, POST, PUT or DELETE)

3) PATH is a path on the server.

4) HANDLER is the function executed when the route is matched

var express = require('express');
var app = express();
app.route('/Node').get(function(req,res)
{
    res.send("Tutorial on Node");
});
app.route('/Angular').get(function(req,res)
{
    res.send("Tutorial on Angular");
});
app.get('/',function(req,res){
    res.send('Welcome to Guru99 Tutorials');
}));
app.get("/items/:vegetable", (req, res) => {
let veg = req.params.vegetable;
res.send(`This is the page for ${veg}`);
});

middleware:

app.use((req, res, next) => {
console.log(`request made to: ${req.url}`);
next();
});
// An example middleware function
var a_middleware_function = function(req, res, next) {
  // ... perform some operations
  next(); // Call next() so Express will call the next middleware function in the chain.
}

// Function added with use() for all routes and verbs
app.use(a_middleware_function);

// Function added with use() for a specific route
app.use('/someroute', a_middleware_function);

// A middleware function added for a specific HTTP verb and route
app.get('/', a_middleware_function);

Para archivos estáticos:

app.use(express.static('public'));

Servidor muy sencillo

const routeResponseMap = {
  "/info": "<h1>Info Page</h1>",
  "/contact": "<h1>Contact Us</h1>",
  "/about": "<h1>Learn More About Us.</h1>",
  "/hello": "<h1>Say hello by emailing us here</h1>",
  "/error": "<h1>Sorry the page you are looking for is not here.</h1>"
};

const port = 3000,
  http = require("http"),

  app = http.createServer((req, res) => {
    res.writeHead(200, {
      "Content-Type": "text/html"
    });
    if (routeResponseMap[req.url]) {
      res.end(routeResponseMap[req.url]);
    } else {
      res.end("<h1>Welcome!</h1>");
    }
  });
app.listen(port);
console.log(`The server has started and is listening on port number:${port}`);

Chat: un ejemplo

Necesitamos instalar express y socket:

npm i express

npm i socket.io

 

server.js


var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
socket.on('chat message', function (msg) {
io.emit('chat message', msg);
});
});

http.listen(1337, function () {
console.log('escuchando en *:1337');
});

index.html


<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font: 13px Helvetica, Arial;
}

form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}

form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: .5%;
}

form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}

#messages {
list-style-type: none;
margin: 0;
padding: 0;
}

#messages li {
padding: 5px 10px;
}

#messages li:nth-child(odd) {
background: #eee;
}
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function (e) {
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function (msg) {
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>

Añadimos log. En server.js:

var fs = require('fs');

fs.open('log.txt', 'w', function (err, file) {
    if (err) throw err;
    console.log('Creado!');
});
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

Después del emit:

  fs.appendFile('log.txt', msg+"\r\n", function (err) {
            if (err) throw err;
            console.log('Guardado!');
        });

Node

Por qué usar Node
https://www.toptal.com/nodejs/por-que-demonios-usaria-node-js-un-tutorial-caso-por-caso

Un tutorial en castellano:

https://www.nodebeginner.org/index-es.html

w3school nos quiere:

https://www.w3schools.com/nodejs/

Crear una api:

https://www.imaginaformacion.com/tutorial/aprende-nodejs-tutorial-de-primeros-pasos/

Tutorial completo:

https://www.guru99.com/node-js-tutorial.html

Oficial:
https://nodejs.org/api/synopsis.html