我正在尝试构建一个模块函数,该函数将使用Sharp调整传递到其中的图像的大小。我将图像数据完美地记录在下面给出的.then()
中,但当我return
得到相同的结果时,结果是undefined
。
请帮我找出我在这里做错了什么。
模块
exports.scaleImg = function (w,h,givenPath){
let toInsertImgData;
sharp(givenPath)
.resize(w, h)
.jpeg({
quality: 80,
chromaSubsampling: "4:4:4",
})
.toFile(compressedImgPath)
.then(() => {
fsPromises.readFile(compressedImgPath).then((imgData) => {
toInsertImgData = {
data: imgData,
contentType: "image/jpeg",
};
console.log(toInsertImgData);
return(toInsertImgData);
});
});
}
这里CCD_ 4只是根目录中的文件夹的路径。
服务器文件
const imageScalingModule = require(__dirname+"/modules.js");
app.post("/compose",upload.fields([{ name: "propic" }, { name: "image" }]),
(req, res) => {
console.log(imageScalingModule.scaleImg(640, 480, req.files.image[0].path));
});
then()
返回一个promise,因此您需要在/compose
处理程序中更改代码以等待promise的解析(我使用async/await
,但您也可以执行scaleImg(...).then()
(:
app.post("/compose",upload.fields([{ name: "propic" }, { name: "image" }]),
async (req, res) => {
const res = await imageScalingModule.scaleImg(640, 480, req.files.image[0].path);
console.log(res);
res.send(res); // you probably want to do something like this, otherwise the request hangs
});