如何解决如何将.then中的值从Node.js模块返回到服务器文件?
我正在尝试构建一个模块功能,该功能将调整使用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);
});
});
}
这里compressedImgPath
只是根目录中文件夹的路径。
服务器文件
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()
returns a promise,因此您需要在/compose
处理程序中更改代码,以等待承诺解决(我使用的是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
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。