Detect extension in a directory using node js
Jalal 🚀

Jalal 🚀 @jalal246

About: working on [DFlex](https://github.com/dflex-js/dflex) come and join me

Joined:
Jan 7, 2019

Detect extension in a directory using node js

Publish Date: Apr 7 '20
16 6

Reading files from any package is essential before production. But since we as developers love automating things. Validating package accessibility and detect extensions among other things should be done by code.

The good news is, this can be achieved easily in the node file system.

let's start by working on getting a file extension. We have input: filename.extension splitting the input by "." should achieve our goal easily.

`filename.extension`.split(".") 
// (2) ["filename", "extension"]

`filename.test.extension`.split(".");
// (3) ["filename", "test", "extension"]
Enter fullscreen mode Exit fullscreen mode

As you notice, we need to get the last element of the result. This can be done in different ways. One of them is using pop which returns the last element of the array.

function getExtension(fileFullName) {
  return fileFullName.split(".").pop();
}
Enter fullscreen mode Exit fullscreen mode

We still have a problem. We don't have the file full name. We actually have to auto-detect the extension by knowing the project root.

The first step, using readdirSync to read all files that exist in our directory.

const files = fs.readdirSync(dir);

// (4) [ 'a.js', 'b.js', 'index.js', 'package.json' ]
Enter fullscreen mode Exit fullscreen mode

Then, we can use find which returns the value of the first element that satisfies function result.

const found = [10, 20, 30].find((number) => number > 10);
// 20
Enter fullscreen mode Exit fullscreen mode

Now let's update our function

import fs from "fs";

function getExtension(rootDir, entry) {
  const files = fs.readdirSync(rootDir);
  // (4) [ 'a.js', 'b.ts', 'index.js', 'README.md', 'package.json' ]

  const filename = files.find((file) => {
    // return the first files that include given entry
    return file.includes(entry);
  });

  const extension = filename.split(".").pop();

  return extension;
}

// reading form current directory
const result = getExtension(".", "b");

// result: ts
Enter fullscreen mode Exit fullscreen mode

We can still upgrade our function, as we usually have an index as default entry from the current directory.

function getExtension(rootDir = ".", entry = "index") {
  //
}

const result = getExtension();

// result: js
Enter fullscreen mode Exit fullscreen mode

Our mission is not finished yet, but that's enough for now. Next, we will build validate together.

See you soon!


Do you like it? Please leave ⭐️. I appreciate any feedback 👋👋👋

Comments 6 total

  • David Velasco
    David VelascoApr 7, 2020

    In Node.js, personally I prefer to use the built-in path methods.

    path.parse

    const filepath = 'path/to/file.js';
    path.parse(filepath).ext;  // => .js
    

    path.extname

    const filename = 'file.js';
    path.extname(filename);. // => .js
    

    In any case, make sure you check the returns of split and pop.

    • String.prototype.split() can return an empty string if the separator is the last character of the string; or the entire string if the separator is not found.
    • Array.prototype.pop() can return undefined when used on an empty array.
    • Jalal 🚀
      Jalal 🚀Apr 7, 2020

      Thanks, David!

      Agreed. Using built-in methods are always better than reinventing the wheel. But, we still need to read project entry assuming it's index without knowing the extension. Is It .ts or .js?

      These built-ins, helpful when knowing the full name with the extension included file.js. However, I tried to introduce a method to extract an anonymous extension.

    • Daniel Hillmann
      Daniel HillmannApr 7, 2020

      Was about to comment this, but you were faster than me. Totally agreed here :)

  • mkenzo_8
    mkenzo_8Apr 7, 2020

    You could use the path module too, see : nodejs.org/api/path.html#path_path...

    My version:

    import path from 'path'
    const getExtension = file => path.extname(file).slice(1)
    
  • Scott Simontis
    Scott SimontisApr 7, 2020

    Also keep in mind that some files have a multipart extension (.tar.gz) and files can begin with a period (.bashrc, .profile, and other hidden files).

Add comment