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条回答
Fickle 薄情
2楼-- · 2019-02-01 03:51

If you're using lodash, you can use this simple oneliner:

// returns part1/part2/part3
['part1/', '/part2', '/part3/'].map((s) => _.trim(s, '/')).join('/')

inspired by @Peter Dotchev's answer

查看更多
叛逆
3楼-- · 2019-02-01 03:55

No, you should not use path.join() to join URL elements.

There's a package for doing that now. So rather than reinvent the wheel, write all your own tests, find bugs, fix them, write more tests, find an edge case where it doesn't work, etc., you could use this package.

url-join

https://github.com/jfromaniello/url-join

Install

npm install url-join

Usage

var urljoin = require('url-join');

var fullUrl = urljoin('http://www.google.com', 'a', '/b/cd', '?foo=123');

console.log(fullUrl);

Prints:

'http://www.google.com/a/b/cd?foo=123'

查看更多
beautiful°
4楼-- · 2019-02-01 03:58

This is what I use:

function joinUrlElements() {
  var re1 = new RegExp('^\\/|\\/$','g'),
      elts = Array.prototype.slice.call(arguments);
  return elts.map(function(element){return element.replace(re1,""); }).join('/');
}

example:

url = joinUrlElements(config.mgmtServer, '/v1/o/', config.org, '/apps');
查看更多
登录 后发表回答