【发布时间】:2019-04-16 19:29:09
【问题描述】:
我正在尝试做一个简单的函数来调整存储中新上传的图像的大小。我使用以下方法来帮助我做到这一点:
import { tmpdir } from 'os';
import { join, dirname } from 'path';
import * as sharp from 'sharp';
import * as fs from 'fs-extra';
这段代码执行时:
await bucket.file(filePath).download({
destination: tmpFilePath
});
我在 Google Cloud Function 日志中收到以下错误:
错误:ENOENT:没有这样的文件或目录,打开 '/tmp/images/1542144115815_Emperor_penguins.jpg' at Error (native)
这里是完整的代码[segment]:
const gcs = admin.storage();
const db = admin.firestore();
import { tmpdir } from 'os';
import { join, dirname } from 'path';
import * as sharp from 'sharp';
import * as fs from 'fs-extra';
export const imageResize = functions.storage
.object()
.onFinalize(async object => {
console.log('> > > > > > > 1.3 < < < < < < <');
const bucket = gcs.bucket(object.bucket);
console.log(object.name);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const tmpFilePath = join(tmpdir(), object.name);
const thumbFileName = 'thumb_' + fileName;
const tmpThumbPath = join(tmpdir(), thumbFileName);
console.log('step 1');
// Resizing image
if (fileName.includes('thumb_')) {
console.log('exiting function');
return false;
}
console.log('step 2');
console.log(`filePath: ${filePath}`);
console.log(`tmpFilePath: ${tmpFilePath}`);
await bucket.file(filePath).download({
destination: tmpFilePath
});
console.log('step 3');
await sharp(tmpFilePath)
.resize(200, 200)
.toFile(tmpThumbPath);
await bucket.upload(tmpThumbPath, {
destination: join(dirname(filePath), thumbFileName)
});
更新 1:添加 await fs.ensureDir(tmpFilePath); 以确保文件路径存在。现在收到一个新错误:
错误:EINVAL:无效参数,在错误时打开“/tmp/images/1542146603970_mouse.png”(本机)
更新 2 已解决:在下面添加了一个解决方案作为答案。
【问题讨论】:
标签: node.js google-cloud-firestore google-cloud-storage google-cloud-functions