简体   繁体   English

按名称在目录中搜索文件(不知道扩展名)

[英]Search for a file in directory by it's name (without knowing extension)

I want to find a file in a specific directory by it's name and without knowing it's extension我想通过名称在特定目录中查找文件,而不知道它的扩展名

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

As you see I am adding .png at the end of the path that I want to send it as a response but sometimes I want to save some files that they are not PNG file如您所见,我在路径末尾添加了.png ,我想将其作为响应发送,但有时我想保存一些不是 PNG 文件的文件

Thank you谢谢

I solved this by saving file extension during saving file information into the database我通过在将文件信息保存到数据库中时保存文件扩展名来解决这个问题

And when I send request for getting image response I get the file extension and necessary information for finding it in the goal directory and send the file into the response.当我发送获取图像响应的请求时,我会获得文件扩展名和在目标目录中找到它所需的信息,并将文件发送到响应中。 Here's my code:这是我的代码:

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

But if anyone knows a solution that I mentioned in my question I would also appreciate it if they shared it.但是,如果有人知道我在问题中提到的解决方案,如果他们分享了,我也会很感激。

I want to find a file in a specific directory by it's name and without knowing it's extension我想通过它的名字在特定目录中找到一个文件,而不知道它的扩展名

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

As you see I am adding .png at the end of the path that I want to send it as a response but sometimes I want to save some files that they are not PNG file如您所见,我在路径的末尾添加了.png ,我想将其作为响应发送,但有时我想保存一些不是 PNG 文件的文件

Thank you谢谢

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

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