我使用promise函數和Jimp來調整圖像大小,將其保存在文件夾中,然後將路徑返回到新的調整大小的圖像。Nodejs:Promise在任務完成之前解決問題
但是,在中的resolve()
函數在image.resize().write()
完成之前被觸發,這意味着我的應用程序因爲無法找到新文件而崩潰。
任何幫助將不勝感激。
const fs = require('fs');
const path = require('path');
const jimp = require('jimp');
const resizeWidth = function(file, width) {
return new Promise((resolve, reject) => {
jimp.read(path.join(__dirname, '..', 'assets', 'images', file), (err, image) => {
if (err) reject(err);
const xSize = parseInt(width);
image.resize(xSize, jimp.AUTO)
.write(path.join(__dirname, '..', 'assets', 'images', 'tmp', file));
resolve(path.join(__dirname, '..', 'assets', 'images', 'tmp', file));
});
});
};
module.exports = function(server) {
server.get('/images/:name/:width', (req, res) => {
resizeWidth(req.params.name, req.params.width)
.then(() => {
fs.readFile(path.join(__dirname, '..', 'assets', 'images', 'tmp', req.params.name),
(err, newData) => {
if (err) throw err;
res.sendRaw(200, newData, {
'Content-Length': Buffer.byteLength(newData)
});
res.end();
});
})
.catch((err) => {
console.log(err);
});
});
};
您可以只執行'path.join(__ dirname,'../assets/images/tmp',file)',介意。還要注意''throw err'會殺死你的服務器;我建議使用'fs.readFile'的promisified版本。 – Ryan
@Ryan,是的,這只是一個初步測試,看看jimp是否能夠滿足項目需求 - 重構將關注你提到的事情。 –
哦,並且絕對不讀取和響應'path.join(...,'tmp',req.params.name)'的內容而不驗證或轉換'req.params.name',除非您希望客戶端讀取/寫訪問權限(取決於權限 - 兩者同樣不好)使用'?name = ../../sensitive-config'在系統上的任何文件。我推薦一個UUID或散列。 – Ryan