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

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

    There are other working answers, but I went with the following. A little path.join/URL combo.

    const path = require('path');
    //
    const baseUrl = 'http://ejemplo.mx';
    // making odd shaped path pieces to see how they're handled.
    const pieces = ['way//', '//over/', 'there/'];
    //
    console.log(new URL(path.join(...pieces), baseUrl).href);
    // http://ejemplo.mx/way/over/there/
    
    // path.join expects strings. Just an example how to ensure your pieces are Strings.
    const allString = ['down', 'yonder', 20000].map(String);
    console.log(new URL(path.join(...allString), baseUrl).href);
    // http://ejemplo.mx/down/yonder/20000
    

提交回复
热议问题