在 Windows 上的 NodeJS 上使用 path.join 创建 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12722865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:53:46  来源:igfitidea点击:

Using path.join on NodeJS on Windows to create URL

windowsnode.jsurlpath

提问by jdotjdot

I have two dynamic pieces of a URL that I'm trying to join together to make a full URL. Since I don't know the exact strings I'll be joining, I want to use a path-joining library to avoid string-joining errors like "http://www.mysite.com/friends//12334.html", which has an extra slash, etc.

我有两个动态的 URL 片段,我试图将它们连接在一起以形成完整的 URL。由于我不知道我将要加入的确切字符串,我想使用路径连接库来避免字符串连接错误"http://www.mysite.com/friends//12334.html",例如带有额外斜杠等的字符串连接错误。

I am working on a Windows 7 Home computer using Node.js.

我正在使用 Node.js 在 Windows 7 家用计算机上工作。

I tried using the pathlibrary's path.join(...), but because I am on Windows, it turned all of the forward slashes backwards, which is obviously incorrect for a URL. Example:

我尝试使用path库的path.join(...),但因为我在 Windows 上,它将所有正斜杠向后转,这对于 URL 显然是不正确的。例子:

var path = require('path'),
    joined = path.join('http://www.mysite.com/', '/friends/family');

console.log(joined);
// Prints:
// http:\www.miserable.com\friends\family

What function or library can I use to join pieces of a URL together on Windows? Alternatively, how can I get path.jointo force UNIX-style separators rather than those of Windows?

在 Windows 上,我可以使用什么函数或库将 URL 的各个部分连接在一起?或者,如何path.join强制使用 UNIX 样式的分隔符而不是 Windows 样式的分隔符?

采纳答案by ebohlman

URLs aren't filesystem paths, so nothing in pathis applicable to your requirements. I'd suggest using url.resolve()if it meets your needs, or url.format()if not. Note that you can't simply substitute either for path.join()in your code, since they require different arguments. Read the documentation carefully.

URL 不是文件系统路径,因此没有任何path内容适用于您的要求。url.resolve()如果它满足您的需求,我建议使用,或者url.format()如果不满足。请注意,您不能简单地替换path.join()代码中的任何一个,因为它们需要不同的参数。仔细阅读文档。

回答by blak3r

url.resolveisn't what I thought it'd be at first glance... Notice how dir1 is dropped in 2nd example

url.resolve乍一看不是我想的那样...注意 dir1 在第二个示例中是如何删除的

url.resolve('/one/two/three', 'four')         // '/one/two/four'
url.resolve('http://domain.com/dir1', 'dir2');   // 'http://domain.com/dir2  (dir1 is gone!)

Here's a simple join method I wrote:

这是我写的一个简单的连接方法:

    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;
    }

Sample:

样本:

// 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', "/") );

OUTPUT:

输出:

../something/else
../something/else
something-else
something-is-up
something-is-up
../something/else
../something/else
somedomain.com/somepath
http://somedomain.com/somepath
/somepath

回答by P. Roebuck

...how can I get path.join to force UNIX-style separators rather than those of Windows?

...我怎样才能让 path.join 强制使用 UNIX 风格的分隔符而不是 Windows 风格的分隔符?

While (as @ebohlman noted) URLs aren't filesystem paths, path.posix.join()could be used to create the URL.pathnamecomponent.

虽然(正如@ebohlman 指出的)URL 不是文件系统路径,path.posix.join()但可用于创建URL.pathname组件。

const path = require('path');
const url = require('url');

const origin = 'http://www.example.com/';
const pathname = path.posix.join(path.posix.sep, 'friends', 'family');

// All at once...
const myURL = new URL(pathname, origin);
console.log(myURL.href);
// => 'http://www.example.com/friends/family'

// In steps...
const myURL2 = new URL(origin);
console.log(myURL2.href);
// => 'http://www.example.com/'
myURL2.pathname = pathname;
console.log(myURL2.href);
// => 'http://www.example.com/friends/family'