Aaron
Aaron

Reputation: 1332

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

Upvotes: 46

Views: 34239

Answers (4)

scientist strong
scientist strong

Reputation: 21

decodeURIComponent(path.basename('http://localhost/node-v18.12.1-x64.msi'))

node-v18.12.1-x64.msi

Upvotes: 2

Alex G
Alex G

Reputation: 1610

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

Upvotes: 10

dakab
dakab

Reputation: 5875

Your example can easily be dealt with using Node.js’s url module:

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

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 ----^  */

Upvotes: -1

Cheery
Cheery

Reputation: 16214

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

Upvotes: 95

Related Questions