newbiedev
newbiedev

Reputation: 3596

nodejs - get filename from url

I have this kind of link in my Node.js script:

148414929_307508464041827_8013797938118488137_n.mp4.m4a?_nc_ht=scontent-mxp1-1.cdninstagram.com&_nc_ohc=_--i1eVUUXoAX9lJQ-u&ccb=7-4&oe=60835C8D&oh=61973532a48cb4fb62ac6711e7eba82f&_nc_sid=fa

I'm trying using this code to get the name to save it as an audio file but I'm not able to get the file extension .mp4.m4a from the URL:

const filename = path.basename(data.message.voice_media.media.audio.audio_src);

How I can get the file extension to remove the last part of the URL correctly? I'm able to save the files and if I remove the part of the name before the desired extension it will play without problems.

UPDATE

As suggested in the comments, I've read the linked question but in my case, I don't need to get only the file extension but the first part of the URL that already contains the needed audio extension that is: 148414929_307508464041827_8013797938118488137_n.mp4.m4a.

Upvotes: 1

Views: 3549

Answers (1)

sergdenisov
sergdenisov

Reputation: 8572

I recommend using URL() constructor (works both in browsers and Node.js) because you can be sure your URL is valid:

const url = 'https://test.com/path/148414929_307508464041827_8013797938118488137_n.mp4.m4a?_nc_ht=scontent-mxp1-1.cdninstagram.com&_nc_ohc=_--i1eVUUXoAX9lJQ-u&ccb=7-4&oe=60835C8D&oh=61973532a48cb4fb62ac6711e7eba82f&_nc_sid=fa';

let filename = '';
try {
  filename = new URL(url).pathname.split('/').pop();
} catch (e) {
  console.error(e);
}
console.log(`filename: ${filename}`);

Upvotes: 4

Related Questions