簡體   English   中英

按名稱在目錄中搜索文件(不知道擴展名)

[英]Search for a file in directory by it's name (without knowing 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) ;
})

如您所見,我在路徑末尾添加了.png ,我想將其作為響應發送,但有時我想保存一些不是 PNG 文件的文件

謝謝

我通過在將文件信息保存到數據庫中時保存文件擴展名來解決這個問題

當我發送獲取圖像響應的請求時,我會獲得文件擴展名和在目標目錄中找到它所需的信息,並將文件發送到響應中。 這是我的代碼:

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

但是,如果有人知道我在問題中提到的解決方案,如果他們分享了,我也會很感激。

我想通過它的名字在特定目錄中找到一個文件,而不知道它的擴展名

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 文件的文件

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM