Can I use require(“path”).join to safely concatena

2019-02-01 03:12发布

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

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

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

If not, what way would you suggest for doing this without writing code full of ifs.

9条回答
Deceive 欺骗
2楼-- · 2019-02-01 03:38

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

It sounds like you want url.resolve. From the Node docs:

url.resolve('/one/two/three', 'four')         // '/one/two/four'
url.resolve('http://example.com/', '/one')    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two') // 'http://example.com/two'

Edit: As Andreas correctly points out in a comment, url.resolve 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".

查看更多
爷的心禁止访问
3楼-- · 2019-02-01 03:41

If you use Angular, you can use Location:

import { Location } from '@angular/common';
// ...
Location.joinWithSlash('beginning', 'end');

Works only on 2 arguments though, so you have to chain calls or write a helper function to do that if needed.

查看更多
做个烂人
4楼-- · 2019-02-01 03:42

When I tried PATH for concatenating url parts I run into problems. PATH.join stripes '//' down to '/' and this way invalidates an absolute url (eg. http://... -> http:/...). For me a quick fix was:

baseurl.replace(/\/$/,"") + '/' + path.replace(/^\//,"") )

or with the solution posted by Colonel Panic:

[pathA.replace(/^\/|\/$/g,""),pathB.replace(/^\/|\/$/g,"")].join("/")
查看更多
ら.Afraid
5楼-- · 2019-02-01 03:48

Axios has a helper function that can combine URLs.

function combineURLs(baseURL, relativeURL) {
  return relativeURL
    ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    : baseURL;
}

Source: https://github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js

查看更多
太酷不给撩
6楼-- · 2019-02-01 03:51

No! On Windows path.join will join with backslashes. HTTP urls are always forward slashes.

How about

> ["posts", "2013"].join("/")
'posts/2013'
查看更多
一纸荒年 Trace。
7楼-- · 2019-02-01 03:51

We do it like this:

var _ = require('lodash');

function urlJoin(a, b) {
  return _.trimEnd(a, '/') + '/' + _.trimStart(b, '/');
}
查看更多
登录 后发表回答