Modulo URL Node.js


Il modulo URL integrato

Il modulo URL divide un indirizzo web in parti leggibili.

Per includere il modulo URL, utilizzare il require() metodo:

var url = require('url');

Analizza un indirizzo con il url.parse() metodo e restituirà un oggetto URL con ciascuna parte dell'indirizzo come proprietà:

Esempio

Suddividi un indirizzo web in parti leggibili:

var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'

File server Node.js

Ora sappiamo come analizzare la stringa di query e nel capitolo precedente abbiamo imparato come fare in modo che Node.js si comporti come un file server. Uniamo i due e serviamo il file richiesto dal cliente.

Crea due file html e salvali nella stessa cartella dei file node.js.

estate.html

<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>

inverno.html

<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>


Crea un file Node.js che apra il file richiesto e restituisca il contenuto al client. Se qualcosa va storto, lancia un errore 404:

demo_fileserver.js:

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    } 
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

Ricordarsi di avviare il file:

Avvia demo_fileserver.js:

C:\Users\Your Name>node demo_fileserver.js

Se hai seguito gli stessi passaggi sul tuo computer, dovresti vedere due risultati diversi quando apri questi due indirizzi:

http://localhost:8080/estate.html

Produrrà questo risultato:

Summer

I love the sun!

http://localhost:8080/inverno.html

Produrrà questo risultato:

Winter

I love the snow!