How to Get File Extension from URL in Node JS?

Sep 16, 2022

.

Admin

How to Get File Extension from URL in Node JS?

Now, let's see the article on how to get file extension from URL in node js. we will help you to give an example of get a file extension from URL in node js. we will help you to give an example of get a file extension from URL in nodejs. This post will give you a simple example of get a file extension from URL in node.js.

I will give you a simple example of get a file extension from URL in nodejs. In this example get a file extension from URL using getExt() in node js.

So let's start following example:

Step 1: Install Node JS


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Step 2: Update server.js file

server.js

const path = require('path');

// Get File Extension

function getExt(str) {

const basename = path.basename(str);

const firstDot = basename.indexOf('.');

const lastDot = basename.lastIndexOf('.');

const extname = path.extname(basename).replace(/(\.[a-z0-9]+).*/i, '$1');

if (firstDot === lastDot) {

return extname;

}

return basename.slice(firstDot, lastDot) + extname;

}

console.log(getExt('https://i.picsum.photos/id/1025/367/267.jpg'));

Output:

.jpg

I hope it can help you...

#Node JS