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

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

    Typescript custom solution:

    export function pathJoin(parts: string[], sep: string) {
      return parts
        .map(part => {
          const part2 = part.endsWith(sep) ? part.substring(0, part.length - 1) : part;
          return part2.startsWith(sep) ? part2.substr(1) : part2;
        })
        .join(sep);
    }
    
    expect(pathJoin(['a', 'b', 'c', 'd'], '/')).toEqual('a/b/c/d');
    expect(pathJoin(['a/', '/b/', 'c/', 'd'], '/')).toEqual('a/b/c/d');
    expect(pathJoin(['http://abc.de', 'users/login'], '/')).toEqual('http://abc.de/users/login');
    

提交回复
热议问题