JavaScript validate file name extension using check-more-types library

In this JavaScript tutorial we learn how to check whether a file has expected file name extension or not using the check-more-types module.

Create the sample project

Firstly we create an empty project with the following command.

mkdir sample-project
cd sample-project
npm init -y

And install the check-more-types module using the following command.

npm install check-more-types --save

How to validate file name extension in JavaScript

In this section we show you how to use the check-more-types library extension() method to check if a given file name string has expected file extension or not.

In the sample-project directory create a new file named check-extension.js as below.


var check = require('check-more-types');

console.log(check.extension('png', '/path/to/file.png'))
console.log(check.extension('txt', '/path/to/file.png'))

const isJs = check.extension('js');


Run the check-extension.js file using the following command.

node check-extension.js
The output is:

More examples of how to use the check.extension() method


var check = require('check-more-types');

var fileName = 'index.js';

if(check.extension('js', fileName)) {
    console.log(fileName + ' is a JavaScript file.');
} else {
    console.log(fileName + ' is not a JavaScript file.');

const isJson = check.extension('json');

if(isJson(fileName)) {
    console.log(fileName + ' is a JSON file.');
} else {
    console.log(fileName + ' is not a JSON file.');

Run the check-extension-examples.js file using the following command.

node check-extension-examples.js
The output is:
index.js is a JavaScript file.
index.js is not a JSON file.

Happy Coding 😊