【发布时间】:2021-12-07 15:22:52
【问题描述】:
我正在尝试在从谷歌云存储流式传输后调整图像大小。流媒体工作正常,但调整大小似乎不起作用。我需要将图像对象传递给sharpjs的resize函数,然后该函数将在API响应中调整并返回图像。
我的代码如下:
const express = require('express')
const {Storage} = require('@google-cloud/storage');
let server = express()
const storage = new Storage();
const bucketName = '<some-bucket-name>'
server.get('/*', async (req, res, next) => {
// Extract the query-parameter
const widthString = req.query.width
const heightString = req.query.height
const format = req.query.format
const fileName = req.path.substring(1);
console.log("url: ", req.path)
// Parse to integer if possible
let width, height
if (widthString) {
width = parseInt(widthString)
}
if (heightString) {
height = parseInt(heightString)
}
// Set the content-type of the response
res.type(`image/${format || 'png'}`)
// Get the resized image
downloadFileStream(fileName).then((imageObj) =>{
resize(imageObj, format, width, height).pipe(res)
})
.catch ((e) =>
console.log(e)
);
})
async function downloadFileStream(fileName){
return await storage.bucket(bucketName).file(fileName).createReadStream().pipe()
}
我在文件下载后应该调用 resize 的方式中遗漏了一些东西。我收到以下错误:
TypeError: Cannot read property 'on' of undefined
at PassThrough.Readable.pipe (internal/streams/readable.js:657:8)
at streamFile (/home/adityam/imageoptimizer/server.js:40:82)
at /home/adityam/imageoptimizer/server.js:30:7
【问题讨论】:
-
查看此代码 ... return await storage.bucket(bucketName).file(fileName).createReadStream().pipe() 我没有得到“await” ...肯定等待接受一个“承诺”并阻塞,直到承诺得到解决。查看文档,我没有看到“pipe()”返回 Promise?哪个源语句引发了异常?
-
return await storage.bucket(bucketName).file(fileName).createReadStream().pipe()这是生成错误的行。在源文档中@github.com/googleapis/nodejs-storage/blob/HEAD/samples/… 似乎采用了文件流。当我跳过 resize() 并直接传递 resp 时,它工作正常。 -
我认为您在函数
download File Stream中缺少存储桶名称,因为变量bucketName已使用但未定义(尽管您已在代码的其他地方全局定义了它) -
@RogelioMonter bucketName 是全局定义的(我已经更新了详细信息)。所以这不是问题。问题是关于如何在 downloadFile 生成的文件流上调用 resize()。
标签: javascript node.js express google-cloud-storage sharp