url.resolve
一見すると思っていたものではありません...2番目の例でdir1がどのようにドロップされているかに注目してください
url.resolve('/one/two/three', 'four') // '/one/two/four'
url.resolve('http://domain.com/dir1', 'dir2'); // 'http://domain.com/dir2 (dir1 is gone!)
これが私が書いた簡単な結合メソッドです:
var _s = require('underscore.string');
/**
* Joins part1 and part2 with optional separator (defaults to '/'),
* and adds the optional prefix to part1 if specified
*
* @param {string} part1
* @param {string} part2
* @param {string} [separator] - defaults to '/'
* @param {string} [prefix] - defaults to empty... pass in "http://" for urls if part1 might not already have it.
* @returns {string}
*/
exports.joinWith = function(part1, part2, separator, prefix) {
var join = "";
var separatorsFound = 0;
if( !separator) { separator = "/"; }
if( !prefix ) { prefix = ""; }
if( _s.endsWith( part1, separator ) ) { separatorsFound += 1; }
if( _s.startsWith( part2, separator) ) { separatorsFound += 1; }
// See if we need to add a join separator or remove one (if both have it already)
if( separatorsFound === 0 ) { join = separator; }
else if( separatorsFound === 2 ) { part1 = part1.substr(0, part1.length - separator.length ); }
// Check if prefix is already set
if( _s.startsWith( part1, prefix ) ) { prefix = ""; }
return prefix + part1 + join + part2;
}
サンプル:
// TEST
console.log( exports.joinWith('../something', 'else') );
console.log( exports.joinWith('../something/', 'else') );
console.log( exports.joinWith('something', 'else', "-") );
console.log( exports.joinWith('something', 'up', "-is-") );
console.log( exports.joinWith('something-is-', 'up', "-is-") );
console.log( exports.joinWith('../something/', '/else') );
console.log( exports.joinWith('../something/', '/else', "/") );
console.log( exports.joinWith('somedomain.com', '/somepath', "/") );
console.log( exports.joinWith('somedomain.com', '/somepath', "/", "http://") );
console.log( exports.joinWith('', '/somepath', "/") );
出力:
../something/else
../something/else
something-else
something-is-up
something-is-up
../something/else
../something/else
somedomain.com/somepath
http://somedomain.com/somepath
/somepath