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

前端 未结 15 528
臣服心动
臣服心动 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:27

    No. path.join() will return incorrect values when used with URLs.

    It sounds like you want new URL(). From the WHATWG URL Standard:

    new URL('/one', 'http://example.com/').href    // 'http://example.com/one'
    new URL('/two', 'http://example.com/one').href // 'http://example.com/two'
    

    Note that url.resolve is now marked as deprecated in the Node docs.

    As Andreas correctly points out in a comment, url.resolve (also deprecated) would only help if the problem is as simple as the example. url.parse also applies to this question because it returns consistently and predictably formatted fields via the URL object that reduces the need for "code full of ifs". However, new URL() is also the replacement for url.parse.

提交回复
热议问题