user2520410
user2520410

Reputation: 479

How do I parse data with url.parse(...)?

I found this sample code of a nodeJS server. I don't understand what this line of code does, what is the true for:

var urlParts = url.parse(req.url, true) 

The following line is also unclear to me. Why is it neccessairy to write data.txt?

fs.writeFileSync("data.txt", data);

SERVER

server = http.createServer(function(req, res) {

  res.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-Origin': 'http://localhost'
  });

  var urlParts = url.parse(req.url, true),
      data = urlParts.query.data;

  fs.writeFileSync("data.txt", data);

  res.end("OK");
});

Upvotes: 0

Views: 3439

Answers (1)

user2226755
user2226755

Reputation: 13159

This line require('url').parse(req.url, true) return URL object (see bottom), and pass true as the second argument to also parse the query.

  • href : The full URL that was originally parsed. Both the protocol and host are lowercased.
  • protocol : The request protocol, lowercased.
  • host : The full lowercased host portion of the URL, including port information.
  • auth : The authentication information portion of a URL.
  • hostname : Just the lowercased hostname portion of the host.
  • port : The port number portion of the host.
  • pathname : The path section of the URL, that comes after the host and before the query, including the initial slash if present.
  • search : The 'query string' portion of the URL, including the leading question mark.
  • path : Concatenation of pathname and search.
  • query : Either the 'params' portion of the query string, or a querystring-parsed object.
  • hash : The 'fragment' portion of the URL including the pound-sign.

See : http://nodejs.org/docs/latest/api/url.html

Upvotes: 6

Related Questions