簡體   English   中英

我如何通過端點向客戶端發送初始響應(res.send 或 res.write),然后通過相同的端點向客戶端發送圖像

[英]How could I send an initial response (res.send or res.write) to the client via endpoint, then via the the same endpoint, send an image to the client

我正在創建一個圖像處理 API,它通過 URL(查詢字符串)從用戶那里獲取圖像和數據,然后處理該圖像,然后將其發回給用戶。 她是代碼的樣子:

export const writeFile = async (width: number, height: number, pathToFullImage: string, pathToThumbImage: string): Promise<void> => {
try {
    //process the image
    let image = await sharp(`${pathToFullImage}.jpeg`).resize(width, height).jpeg().toBuffer();
    fs.writeFile(`${pathToThumbImage}.jpeg`, image);
    
} catch (error) {
    console.log(`Error from async func in writeFile  ${error}`)
}

};

export const readFile = (res: express.Response, pathToThumbImage: string) =>{
try {
    res.sendFile(`${pathToThumbImage}.jpeg`);
} catch (error) {
    console.log(`Error from async func in readFile ${error}`)
}

}

mainEndpoint.get('/api', (req: express.Request, res: express.Response) : void=>{
res.write("API route");

//get the query string from url to be used 
const data: ParsedQs = req.query;

//get the width and the height from 'data' object
let filename = data.filename as string;
let width: number = parseInt(data.width as string);
let height: number = parseInt(data.height as string);

//call the function
writeFile(width, height, pathToFullImage, pathToThumbImage);

//call the readFile function 
// If we didnt use setTimeout, the endpoint will try to read before the file is even written, so to solve this problem, use setTimeOut to make the reading process lag after the writing in the event loop. 
setTimeout(()=>readFile(res, pathToThumbImage), 100);

console.log(data);

res.end(); 

})

代碼如何工作:

第一:我得到查詢字符串,在'mainEndpoint'中處理它們第二:將它們發送到'writeFile'以處理圖像並將其保存在目標文件夾中第三:將它們傳遞給'readFile'以使用'res.sendFile'來發送它們給客戶

問題是:當我嘗試使用“res.write”發送初始響應時,“readFile”不發送圖像?

我怎樣才能讓端點發送初始響應和圖像? 如果我不發送初始響應,盡管一切正常。

嘗試await writeFile調用。 那時您不必設置超時。

//call the function
await writeFile(width, height, pathToFullImage, pathToThumbImage);

//call the readFile function 
setTimeout(()=>readFile(res, pathToThumbImage), 100);

並在writeFile中等待。

const writeFilePromise = util.promisify(fs.writeFile)
await writeFilePromise(`${pathToThumbImage}.jpeg`, image);

最后,根本不要調用它,因為您不能混合使用字符串和文件的返回值。

res.write("API route");

暫無
暫無

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

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