javascript Node.js,从 URL 解析文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27006363/
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-10-28 06:48:34  来源:igfitidea点击:

Node.js, parse filename from URL

javascriptnode.js

提问by Aaron

How can I parse a url?

如何解析网址?

site.com:8080/someFile.txt?attr=100

or

或者

site.com:8080/someFile.txt/?attr=100

I need to get someFile.txt, where is a file name I set by myself as the format (txt or some other).

我需要得到someFile.txt,我自己设置的文件名在哪里作为格式(txt 或其他)。

UPDATE

更新

I tried

我试过

var path = url.parse(req.url).path;

But I still cannot get the path (someFile.txt).

但我仍然无法获得路径(someFile.txt)。

回答by Cheery

Something like this..

像这样的东西..

var url = require("url");
var path = require("path");
var parsed = url.parse("http://example.com:8080/test/someFile.txt/?attr=100");
console.log(path.basename(parsed.pathname));

回答by dakab

Your example can easily be dealt with using Node.js's urlmodule:

使用Node.js 的url模块可以轻松处理您的示例:

var URL = require('url').parse('site.com:8080/someFile.txt?attr=100');
console.log(URL.pathname.replace(/(^\/|\/$)/g,'')); // "someFile.txt"

However, this doesn't work with Node.js's exemplary URL ('cause it's got more path).

但是,这不适用于 Node.js 的示例 URL(因为它有更多路径)。

By truncanting the complete path starting at its rightmost slash, it'll yield the file name:

通过截断从最右边斜杠开始的完整路径,它将产生文件名:

var URL = require('url').parse('http://user:[email protected]:8080/p/a/t/h?query=string#hash');
console.log(URL.pathname.substring(URL.pathname.lastIndexOf('/')+1)); // "h"

And if that idea is considered safe enough for the appliance, we can do it plain:

如果这个想法对于设备来说足够安全,我们可以简单地做到:

var file = url.substring(url.lastIndexOf('/')+1).replace(/((\?|#).*)?$/,'');
                              /* hashes and query strings ----^  */