Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
How to retrieve a file using node.js fs readFile function without specifying the name?

I'm currently stuck trying to retrieve a file from file system in order to send it through api to the client. For my backend I'm using express js I'm using fs library and currently I'm trying to do it with readFile function, but I want to do it without specifying the file name or just the file extension because it will depend from file file will be uploaded from client.

What I tried until now (unsuccessfully) is shown below:

router.get("/info/pic", async (req, res) => {
  const file = await fs.readFile("./images/profile/me.*", (err, data) => {
    if (err) {
      console.log(err);  // Error: ENOENT: no such file or directory, open './images/profile/me.*'
      return;
    }
    console.log(data);
  });
});
const file = await fs.readFile("./images/profile/*.*", (err, data) => {
    if (err) {
      console.log(err);  // Error: ENOENT: no such file or directory, open './images/profile/*.*'
      return;
    }
    console.log(data);
});
const file = await fs.readFile("./images/profile/*", (err, data) => {
    if (err) {
      console.log(err);  // Error: ENOENT: no such file or directory, open './images/profile/*'
      return;
    }
    console.log(data);
});

If I specify the file name everything works fine, like: fs.readFile("./images/profile/me.jpg". but as I said, I don't know for sure the right extension of that file.

Important info: In that directory there will be only one file!

Please help me! Thank you in advance!

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

If there is only one file in the directory, the following loop will have only one iteration:

for await (const file of fs.opendirSync("./images/profile")) {
  var image = fs.readFileSync("./images/profile/" + file.name);
  ...
}
about 4 years ago · Santiago Trujillo Report

0

const fs = require('fs');
fs.readdir('./images/profile', function (err, files) {
    //handling error
    if (err) {
        return console.log('err);
    } 
    files.forEach(function (file) {
        // Do whatever you want to do with the file
    });
});
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!