我正在尝试做一个简单的函数,调整存储中新上传的图像的大小。我使用以下内容来帮助我做到这一点:
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
});
我在谷歌云功能日志中得到以下错误:
错误:ENOENT:没有这样的文件或目录,在错误(本机(处打开'/tmp/images/1542144115815_Emperor_pensions.jpg'
这是完整的代码[段]:
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)
});
UPDATE 1:添加await fs.ensureDir(tmpFilePath);
以确保文件路径存在。现在得到一个新错误:
错误:EINVAL:无效参数,在错误(本机(处打开'/tmp/images/1542146603970_mouse.png'
更新2已解决:添加了一个解决方案作为下面的答案。
我更改了以下代码
来自
const bucket = gcs.bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const tmpFilePath = join(tmpdir(), object.name);
const thumbFileName = 'thumb_' + fileName;
const tmpThumbPath = join(tmpdir(), thumbFileName);
到
const bucket = gcs.bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const thumbFileName = 'thumb_' + fileName;
const workingDir = join(tmpdir(), `${object.name.split('/')[0]}/`);//new
const tmpFilePath = join(workingDir, fileName);
const tmpThumbPath = join(workingDir, thumbFileName);
await fs.ensureDir(workingDir);
正如您所看到的,我创建了一个在路径之间共享的workingDir
,然后运行await fs.ensureDir(workingDir);
来创建路径。这解决了我的问题。
我怀疑您看到该消息是因为您试图写入以下路径:
/tmp/images/1542144115815_Emperor_penguins.jpg
不首先创建父目录:
/tmp/images
您无法将文件写入不存在的本地文件系统文件夹,而且云存储SDK似乎不会为您创建它。