Error: ENOENT: no such file or directory even when file exists in Firebase Cloud Functions

Error: ENOENT: no such file or directory even when file exists in Firebase Cloud Functions

我对 Cloud Functions 比较陌生,一段时间以来一直在尝试解决这个问题。本质上,每当有完整的上传到 Firebase 云存储时,我尝试编写的函数就会被调用。但是,当函数运行s,进行到一半的时候,它运行s出现如下错误:

The following error occured:  { Error: ENOENT: no such file or directory, open '/tmp/dataprocessing/thisisthefilethatiswritten.zip'
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/tmp/dataprocessing/thisisthefilethatiswritten.zip' }

代码如下:

const functions = require('firebase-functions');
const admin = require('firebase-admin')
const inspect = require('util').inspect
const path = require('path');
const os = require('os');
const fs = require('fs-extra');

const firestore = admin.firestore()
const storage = admin.storage()

const runtimeOpts = {
    timeoutSeconds: 540,
    memory: '2GB'
  }

const uploadprocessing = functions.runWith(runtimeOpts).storage.object().onFinalize(async (object) => {
    const filePath = object.name
    const fileBucket = object.bucket
    const bucket_fileName = path.basename(filePath);
    const uid = bucket_fileName.match('.+?(?=_)')
    const original_filename = bucket_fileName.split('_').pop()

    const bucket = storage.bucket(fileBucket);
    const workingDir = path.join(os.tmpdir(), 'dataprocessing/');
    const tempFilePath = path.join(workingDir, original_filename);

    await fs.ensureDir(workingDir)

    await bucket.file(filePath).download({destination: tempFilePath})

    //this particular code block I included because I was worried that the file wasn't
    //being uploaded to the tmp directly, but the results of the function 
    //seems to confirm to me that the file does exist.

    await fs.ensureFile(tempFilePath)
        console.log('success!')
        fs.readdirSync(workingDir).forEach(file => {
            console.log('file found: ', file);
            });
        console.log('post success')
        fs.readdirSync('/tmp/dataprocessing').forEach(file => {
            console.log('tmp file found: ', file);
    })


    fs.readFile(tempFilePath, function (err, buffer) {
        if (!err) {
            //data processing comes here. Please note that half the time it never gets into this
            //loop as instead it goes into the else function below and outputs that error.
        }
        else {
            console.log("The following error occured: ", err);
        }
    })
    fs.unlinkSync(tempFilePath);
    return
})
module.exports = uploadprocessing;

我一直在尝试很多不同的事情,奇怪的是,当我将代码添加到 "if (!err)" 时(由于错误,实际上并没有 运行)它只是任意的有时开始工作非常一致,但是当我添加不同的代码时它停止工作。我本以为问题是由我添加的代码引起的,但是当我也只是 change/add/remove 评论时,错误确实出现了......从技术上讲,这对函数 运行 应该没有影响宁...

有什么想法吗?先感谢您!!! :)

fs.readFile 异步的 和 returns 立即。您的回调函数会在一段时间后使用缓冲区的内容调用。这意味着 fs.unlinkSync 将在读取文件的同时删除文件。这意味着您实际上有一个竞争条件,并且文件可能会在读取之前被删除。

您的代码应该等到读取完成后再继续删除。也许您想改用 fs.readFileSync