Can I use require(“path”).join to safely concatenate urls?

前端 未结 15 530
臣服心动
臣服心动 2020-12-23 13:06

Is this safe to use require(\"path\").join to concatenate URLs, for example:

require(\"path\").join(\"http://example.com\", \"ok\"); 
//returns          


        
15条回答
  •  时光取名叫无心
    2020-12-23 13:41

    This can be accomplished by a combination of Node's path and URL:

    1. Require the packages:
    const nodeUrl = require('url')
    const nodePath = require('path')
    
    1. Start by making a URL object to work with:
    > const myUrl = new nodeUrl.URL('https://example.com')
    
    1. Use pathname= and path.join to construct any possible combination:
    > myUrl.pathname = nodePath.join('/search', 'for', '/something/')
    '/search/for/something/'
    

    (you can see how liberal path.join is with arguments)

    1. At this point your URL reflects the ultimate desired result:
    > myUrl.toString()
    'https://example.com/search/for/something/'
    

    Why this approach?

    This technique uses built-in libraries. The less third-party dependencies the better, when it comes to CVEs, maintenance, etc.

    PS: Never manipulate URLs as strings!

    When I review code I'm adamant about never manipulating URLs as strings manually. For one, look how complicated the spec is.

    Secondly, the absence/presence of a trailing/prefixed slash (/) should not cause everything to break! You should never do:

    const url = `${baseUrl}/${somePath}`
    

    and especially not:

    uri: host + '/' + SAT_SERVICE + '/' + CONSTELLATION + '/',
    

    Of which I have seen.

提交回复
热议问题