skip to Main Content

How could I read a file in FS without having to put the file extension.

e.x: fs.readFile(../hello**.png(without this file extension?**

Tried this and this returned not found.

2

Answers


  1. As @tkausl said, it is not possible because without the file extension, the operating system doesn’t know the type of file, and can’t read it.

    You could try to use the glob module to find a file using a certain pattern.

    Here is an example:

    const glob = require('glob');
    const fs = require('fs');
    
    glob('../hello.*', (err, files) => {
      if (err) throw err;
      if (files.length > 0) {
        fs.readFile(files[0], (err, data) => {
          if (err) throw err;
          console.log(data);
        });
      } else {
        console.log('File not found');
      }
    });
    
    Login or Signup to reply.
  2. Saw an answer using the glob npm package. And it is possible to use, but not necessary. So, why not stick to the built-in modules of Node.js? No need to install any extra packages…

    The code would look like this:

    const { readdirSync, readFileSync } = require('fs');
    const { dirname, parse } = require('path');
    
    function readFileGuessExtension(pathWithNoExtension) {
      try {
        let files = readdirSync(dirname(pathWithNoExtension));
        let name = parse(pathWithNoExtension).base;
        let found = files.find(x => x.indexOf(name) === 0);
        return readFileSync(dirname(pathWithNoExtension) + '/' + found, 'utf-8');
      }
      catch (e) {
        return null;
      }
    }
    
    console.log(readFileGuessExtension('somePathWithoutFileExtension'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search