【问题标题】:Search for a file in directory by it's name (without knowing extension)按名称搜索目录中的文件(不知道扩展名)
【发布时间】:2021-05-03 06:30:53
【问题描述】:

我想通过文件名在特定目录中查找文件,但不知道它的扩展名

app.get("/test/:id", (req, res) => {
    const mongo_id = req.params.id;
    const file_path = __dirname + somepath + mongo_id + ".png"; // I should remove this extension but how to find file ?
    if (!existsSync(file_path)) return res.status(404).end() ; // Check if file exists

    res.sendFile(file_path) ;
})

如您所见,我在路径末尾添加了.png,我想将其作为响应发送,但有时我想保存一些不是 PNG 文件的文件

谢谢

【问题讨论】:

    标签: javascript node.js express directory fs


    【解决方案1】:

    我通过在将文件信息保存到数据库时保存文件扩展名解决了这个问题

    当我发送获取图像响应的请求时,我会获得文件扩展名和在目标目录中找到它所需的信息,并将文件发送到响应中。 这是我的代码:

    app.get("test/:id", (req, res) => {
        const mongo_id = req.params.id;
    
        MyModel.findById(mongo_id, (err, file) => {
            if (err || !file) return res.status(404).end()
    
            const file_path = __dirname + somepath + mongo_id + '.' + file.extension;
            
            if (!existsSync(file_path)) return res.status(404).end();
            res.sendFile(file_path);
        })
    })
    
    

    但是,如果有人知道我在问题中提到的解决方案,如果他们分享,我也将不胜感激。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      相关资源
      最近更新 更多