繁体   English   中英

如何在不指定名称的情况下使用 node.js fs readFile 函数检索文件?

[英]How to retrieve a file using node.js fs readFile function without specifying the name?

我目前正试图从文件系统中检索文件,以便通过 api 将其发送到客户端。 对于我的后端,我使用的是 express js,我正在使用fs库,目前我正在尝试使用readFile函数来执行此操作,但我想在不指定文件名或仅文件扩展名的情况下执行此操作,因为它将取决于文件文件将从客户端上传。

我到目前为止尝试的(不成功)如下所示:

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

如果我指定文件名,一切正常,例如: fs.readFile("./images/profile/me.jpg" 。但正如我所说,我不确定该文件的正确扩展名。

重要信息:在该目录中将只有一个文件!

请帮我! 先感谢您!

如果目录中只有一个文件,则以下循环将只有一次迭代:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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