[英]nodejs - get filename from url
I have this kind of link in my Node.js script:我的 Node.js 脚本中有这种链接:
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:我正在尝试使用此代码获取名称以将其保存为音频文件,但我无法从 URL 获取文件扩展名
.mp4.m4a
:
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?如何获得文件扩展名以正确删除 URL 的最后一部分? 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
.正如评论中所建议的,我已经阅读了链接的问题,但在我的情况下,我不需要只获取文件扩展名,而是 URL 的第一部分已经包含所需的音频扩展名:
148414929_307508464041827_8013797938118488137_n.mp4.m4a
。
I recommend using URL() constructor
(works both in browsers and Node.js) because you can be sure your URL is valid:我建议使用
URL() constructor
(适用于浏览器和 Node.js),因为您可以确定您的 URL 是有效的:
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}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.