Google Cloud Function-错误:ENOENT:没有这样的文件或目录

时间:2018-11-13 21:39:42

标签: node.js google-cloud-firestore google-cloud-storage google-cloud-functions

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

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”

这是完整的代码[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 :在下面添加了解决方案作为答案

2 个答案:

答案 0 :(得分:0)

我怀疑您会看到该消息,因为您尝试写入此路径:

/tmp/images/1542144115815_Emperor_penguins.jpg

无需先创建父目录:

/tmp/images

您无法将文件写入不存在的本地文件系统文件夹中,并且似乎Cloud Storage SDK不会为您创建该文件。

答案 1 :(得分:0)

我更改了以下代码

发件人

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