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 = 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 =;

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

Problem courtesy of: user2520410


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 :

Solution courtesy of: Hors Sujet


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.