Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js, parse filename from URL

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).

UPDATE

I tried

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

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

like image 687
Aaron Avatar asked Nov 18 '14 23:11

Aaron


People also ask

What is filename in URL?

The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.

What is path Basename?

The path. basename() method returns the filename part of a file path.

What is the purpose of __ filename variable?

To get the absolute path of the current file/code. To get the name of the file currently executing.


2 Answers

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)); 
like image 179
Cheery Avatar answered Sep 19 '22 08:09

Cheery


here's my working code, hope it helps

import path from 'path'  const getBasenameFormUrl = (urlStr) => {     const url = new URL(urlStr)     return path.basename(url.pathname) } 
like image 22
Alex G Avatar answered Sep 18 '22 08:09

Alex G