如何将.then()中的值从Node.js模块返回到服务器文件?
我正在尝试构建一个模块函数,该函数将使用Sharp调整传入其中的图像的大小。 我将图像数据完美地记录在下面给出的如何将.then()中的值从Node.js模块返回到服务器文件?,node.js,asynchronous,es6-promise,node-modules,fs,Node.js,Asynchronous,Es6 Promise,Node Modules,Fs,我正在尝试构建一个模块函数,该函数将使用Sharp调整传入其中的图像的大小。 我将图像数据完美地记录在下面给出的.then()中,但是当我返回同样的结果时,结果却是未定义的 请帮我找出我做错了什么 模块 exports.scaleImg = function (w,h,givenPath){ let toInsertImgData; sharp(givenPath) .resize(w, h) .jpeg({
.then()
中,但是当我返回同样的结果时,结果却是未定义的
请帮我找出我做错了什么
模块
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);
});
});
}
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));
});
这里的compressedImgPath
只是根目录中文件夹的路径
服务器文件
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);
});
});
}
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()
,因此您需要在/compose
-处理程序中更改代码,以等待承诺得到解决(我使用的是async/await
,但您也可以执行scaleImg(…)。然后()
):