Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js url module

Node.js url module

Java FileNode.js Built-in Modules


In Node.js, the url The module is a built-in module used to process and parse URLs (Uniform Resource Locators). It provides a series of practical methods that make it easy to parse, format, and process URL strings.

URL (Uniform Resource Locator) is an address used on the Internet to identify and locate resources, for example:

https://www.example.com:8080/path/to/resource?query=string#hash


Core Methods

The url.parse() method

url.parse() The method is used to parse a URL string into a URL object.

Example

const

url

=

require

(

'url'

)

;

const

urlString

=

'https://www.example.com:8080/path/to/resource?query=string#hash'

;

const

parsedUrl

=

url.

parse

(

urlString

)

;

console.

log

(

parsedUrl

)

;

The output will contain the following properties:

The url.format() method

url.format() The method and the parse() Conversely, it converts a URL object into string form.

Example

const

url

=

require

(

'url'

)

;

const

urlObject

=

{

  protocol

:

'https:'

,

  host

:

'www.example.com:8080'

,

  pathname

:

'/path/to/resource'

,

  query

:

{

query

:

'string'

}

,

  hash

:

'#hash'

}

;

const

formattedUrl

=

url.

format

(

urlObject

)

;

console.

log

(

formattedUrl

)

;

// Output: https://www.example.com:8080/path/to/resource?query=string#hash

The url.resolve() method

url.resolve() The method is used to resolve a target URL relative to a base URL.

Example

const

url

=

require

(

'url'

)

;

const

baseUrl

=

'https://www.example.com/path/'

;

const

relativeUrl

=

'to/resource'

;

const

resolvedUrl

=

url.

resolve

(

baseUrl

,

relativeUrl

)

;

console.

log

(

resolvedUrl

)

;

// Output: https://www.example.com/path/to/resource


The structure of a URL object

A complete URL object typically contains the following properties:

  1. Protocol (protocol) - Such as 'http:' or 'https:'
  2. Authentication info (auth) - Contains the username and password
  3. Host (host) - Host name and port number
  4. Host name (hostname) - Host name only
  5. Port (port) - Port number
  6. Path (pathname) - Resource path
  7. Query string (search) - Query string starting with '?'
  8. Query parameters (query) - The parsed result of the query string
  9. Fragment identifier (hash) - Fragment identifier starting with '#'

The new URL API

Node.js also provides a new API based on the WHATWG URL standard:

The URL class

Example

const

{

URL

}

=

require

(

'url'

)

;

const

myUrl

=

new

URL

(

'https://www.example.com:8080/path/to/resource?query=string#hash'

)

;

console.

log

(

myUrl.

protocol

)

;

// 'https:'

console.

log

(

myUrl.

hostname

)

;

// 'www.example.com'

console.

log

(

myUrl.

port

)

;

   

// '8080'

console.

log

(

myUrl.

pathname

)

;

// '/path/to/resource'

console.

log

(

myUrl.

search

)

;

 

// '?query=string'

console.

log

(

myUrl.

hash

)

;

   

// '#hash'

The URLSearchParams class

URLSearchParams It provides convenient methods for handling query strings:

Example

const

{

URL

,

URLSearchParams

}

=

require

(

'url'

)

;

const

myUrl

=

new

URL

(

'https://example.com/?name=John&age=30'

)

;

const

params

=

new

URLSearchParams

(

myUrl.

search

)

;

// Get a parameter

console.

log

(

params.

get

(

'name'

)

)

;

// 'John'

console.

log

(

params.

get

(

'age'

)

)

;

 

// '30'

// Add a parameter

params.

append

(

'city'

,

'New York'

)

;

// Delete a parameter

params.

delete

(

'age'

)

;

// Convert to string

console.

log

(

params.

toString

(

)

)

;

// 'name=John&city=New+York'


Practical Application Scenarios

1. Parse the request URL

Parse the URL of a client request in an HTTP server:

Example

const

http

=

require

(

'http'

)

;

const

url

=

require

(

'url'

)

;

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

 

const

parsedUrl

=

url.

parse

(

req.

url

,

true

)

;

 

  console.

log

(

'Path:'

,

parsedUrl.

pathname

)

;

  console.

log

(

'Query:'

,

parsedUrl.

query

)

;

 

  res.

end

(

'URL parsed successfully'

)

;

}

)

;

server.

listen

(

3000

)

;

2. Build API endpoints

Use the URL module to build RESTful API endpoints:

Example

const

http

=

require

(

'http'

)

;

const

url

=

require

(

'url'

)

;

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

 

const

parsedUrl

=

url.

parse

(

req.

url

,

true

)

;

 

const

path

=

parsedUrl.

pathname

;

 

 

if

(

path

===

'/api/users'

)

{

   

// Handle user-related requests

    res.

end

(

JSON.

stringify

(

{

users

:

[

'John'

,

'Jane'

]

}

)

)

;

 

}

else

if

(

path

===

'/api/products'

)

{

   

// Handle product-related requests

    res.

end

(

JSON.

stringify

(

{

products

:

[

'Phone'

,

'Laptop'

]

}

)

)

;

 

}

else

{

    res.

statusCode

=

404

;

    res.

end

(

'Not Found'

)

;

 

}

}

)

;

server.

listen

(

3000

)

;

3. Handle query parameters

Example

const

http

=

require

(

'http'

)

;

const

url

=

require

(

'url'

)

;

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

 

const

parsedUrl

=

url.

parse

(

req.

url

,

true

)

;

 

const

query

=

parsedUrl.

query

;

 

 

if

(

parsedUrl.

pathname

===

'/search'

)

{

   

const

keyword

=

query.

q

||

''

;

   

const

page

=

parseInt

(

query.

page

)

||

1

;

   

    res.

end

(

`Searching

for

"${keyword}"

on page $

{

page

}

`

)

;

 

}

}

)

;

server.

listen

(

3000

)

;


Best Practices

  1. Always validate URLs - When handling URLs provided by users, always validate their validity
  2. Use the new API - Prefer the WHATWG URL API, which better conforms to modern standards
  3. Handle Exceptions - Use try-catch to handle errors that may occur during URL parsing
  4. Encode special characters - Uses encodeURIComponent() Encode special characters in query parameters
  5. Security Considerations - When handling redirects, validate the target URL to prevent open redirect vulnerabilities

Example

// Security example: validate the redirect URL

function

isValidRedirect

(

url

)

{

 

const

allowedDomains

=

[

'example.com'

,

'trusted-site.com'

]

;

 

const

parsedUrl

=

new

URL

(

url

)

;

 

return

allowedDomains.

includes

(

parsedUrl.

hostname

)

;

}

By mastering Node.js's url module, you can easily handle a variety of URL-related operations and build more robust and secure web applications.

Java FileNode.js Built-in Modules