简体   繁体   中英

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!

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);
  ...
}
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
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM