Google Cloud Function-错误:ENOENT:没有这样的文件或目录 [英] Google Cloud Function - Error: ENOENT: no such file or directory

查看:6
本文介绍了Google Cloud Function-错误:ENOENT:没有这样的文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行一个简单的函数,用于调整存储中新上载的图像的大小。我使用以下方法来帮助我做到这一点:

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函数日志中看到以下错误

错误:环境:没有这样的文件或目录,请在出错时打开‘/tmp/images/1542144115815_Emperor_penguins.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)
        });

更新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);创建路径。这解决了我的问题。

这篇关于Google Cloud Function-错误:ENOENT:没有这样的文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆