Firebase - Node Cloud Функции триггеров разбора ошибок: не удается найти модуль 'firebase-functions' - PullRequest
0 голосов
/ 05 октября 2018

У меня постоянно возникала эта проблема при попытке развертывания.Первоначально я был в состоянии развернуть один раз, когда была только начальная облачная функция «здравствуй, мир» для firebase.

У меня установлен Node 8, и я понял, что это может быть моей проблемой.Я выполнил поиск по этому поводу и обнаружил, что это нормально, если вы укажете движок, например:

фрагмент кода package.json

 "engines": {
    "node": "8"
  },

, но после добавления этого я получаю тот же результат,

Вот мой полный пакет. Json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "@google-cloud/storage": "^2.0.3",
    "busboy": "^0.2.14",
    "cors": "^2.8.4",
    "firebase-admin": "^6.0.0",
    "firebase-functions": "^2.0.5",
    "request-promise": "^4.2.2",
    "uuid": "^3.3.2"
  },
  "engines": {
    "node": "8"
  },
  "private": true
}

и вот мой index.js в моей папке функций

'use strict';
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//

const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const Busboy = require('busboy');
const os = require('os');
const path = require('path');
const fs = require('fs');
const fbAdmin = require('firebase-admin');
const uuid = require('uuid/v4');

// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });
const gcconfig = {
  projectId: 'rs-0001',
  keyFilename: 'rs-0001.json'
};

const gcs = require('@google-cloud/storage')(gcconfig);

// exports.helloWorld = functions.https.onRequest((request, response) => {
//     response.send("Hello from Firebase!");
//    });

   
fbAdmin.initializeApp({
  credential: fbAdmin.credential.cert(require('./rs-0001.json'))
});

exports.storeImage = functions.https.onRequest((req, res) => {
  return cors(req, res, () => {
    if (req.method !== 'POST') {
      return res.status(500).json({ message: 'Not allowed.' });
    }

    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith('Bearer ')
    ) {
      return res.status(401).json({ error: 'Unauthorized.' });
    }

    let idToken;
    idToken = req.headers.authorization.split('Bearer ')[1];

    const busboy = new Busboy({ headers: req.headers });
    let uploadData;
    let oldImagePath;

    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      const filePath = path.join(os.tmpdir(), filename);
      uploadData = { filePath: filePath, type: mimetype, name: filename };
      file.pipe(fs.createWriteStream(filePath));
    });

    busboy.on('field', (fieldname, value) => {
      oldImagePath = decodeURIComponent(value);
    });

    busboy.on('finish', () => {
      const bucket = gcs.bucket('rs-0001.appspot.com');
      const id = uuid();
      let imagePath = 'images/' + id + '-' + uploadData.name;
      if (oldImagePath) {
        imagePath = oldImagePath;
      }

      return fbAdmin
        .auth()
        .verifyIdToken(idToken)
        .then(decodedToken => {
          return bucket.upload(uploadData.filePath, {
            uploadType: 'media',
            destination: imagePath,
            metadata: {
              metadata: {
                contentType: uploadData.type,
                firebaseStorageDownloadTokens: id
              }
            }
          });
        })
        .then(() => {
          return res.status(201).json({
            imageUrl:
              'https://firebasestorage.googleapis.com/v0/b/' +
              bucket.name +
              '/o/' +
              encodeURIComponent(imagePath) +
              '?alt=media&token=' +
              id,
            imagePath: imagePath
          });

          return null
        })
        .catch(error => {
          return res.status(401).json({ error: 'Unauthorized!' });
        });
    });
    return busboy.end(req.rawBody);
  });
});

Я использовал предыдущие предложения по аналогичным вопросам, предлагая перейти в каталог / functions / и выполнить установку npm , а затем перейти кпредыдущий каталог и запустите

firebase deploy --only functions

, который возвращает меня к

i  functions: preparing functions directory for uploading...

Error: Error parsing triggers: Cannot find module 'firebase-functions'

Try running "npm install" in your functions directory before deploying.

Я запустил его с --debug, чтобы получить

i  functions: preparing functions directory for uploading...
[2018-10-04T15:34:29.744Z] >>> HTTP REQUEST GET https://runtimeconfig.googleapis.com/v1beta1/projects/rs-0001/configs

[2018-10-04T15:34:31.249Z] <<< HTTP RESPONSE 200 content-type=application/json; charset=UTF-8,vary=X-Origin, Referer, Origin,Accept-Encoding, date=Thu, 04 Oct 2018 15:34:31 GMT, server=ESF, cache-control=private, x-xss-protection=1; mode=block, x-frame-options=SAMEORIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="44,43,39,35", accept-ranges=none, connection=close

Error: Error parsing triggers: Cannot find module 'firebase-functions'

Try running "npm install" in your functions directory before deploying.

Я даже пытался

 cd functions && sudo npm i && cd .. && firebase deploy --only functions --debug

прийти с тем же результатом.Я провел часы, казалось бы, с той же проблемой, удалил node_modules, установил все пакеты по отдельности и т. Д. Может кто-нибудь помочь?

node -v

v8.12.0

npm -v

6.4.1

и я установил firebase-tools по всему миру в последней версии и имею .json для проектав том же каталоге ...

Ответы [ 2 ]

0 голосов
/ 30 октября 2018

Был несовместимый пакет.

    "@google-cloud/storage": "^2.0.3",

должен был быть

    "@google-cloud/storage": "^1.7.0",

по какой-то причине, после этого я смог загрузить.Вот рабочая версия моих функций / index.js

    'use strict';

const functions = require('firebase-functions');
const cors = require('cors')({origin: true});
const Busboy = require('busboy');
const os = require('os');
const path = require('path');
const fs = require('fs');
const fbAdmin = require('firebase-admin');
const uuid = require('uuid/v4');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });
const gcconfig = {
    projectId: 'rs-0001',
    keyFilename: 'rs-0001.json'
};

const gcs = require('@google-cloud/storage')(gcconfig);

fbAdmin.initializeApp({credential: fbAdmin.credential.cert(require('./rs-0001.json'))})

exports.storeImage = functions.https.onRequest((request, response) => {
    return cors(req, res, () => {
        if (req.method !== 'POST') {
            return res.status(500).json({message: 'Not allowed mofo.' });
        }
    if (!req.headers.authorization ||
        !req.headers.authorization.startsWith('Bearer ')
        ) { 
        return res.status(401).json({ error: 'Unauthorized '});
    }

    let idToken;
    idToken = req.headers.authorization.split('Bearer ')[1];

    const busboy = new Busboy({headers: req.headers});
    let uploadData;

    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
        const filePath = path.join(os.tmpdir(), filename);
        uploadData = {filePath: filePath, type: mimetype, name: filename};
        file.pipe(fs.createWriteStream(filePath));
    });

    busboy.on('field', (fieldname, value) => {
        oldImagePath = decodeURIComponent(value);
    })

    busboy.on('finish', () => {
        const bucket = gcs.bucket('rs-0001.appspot.com');
        const id = uuid();
        let imagePath = 'images/' + id + '-' + uploadData.name
        if (oldImagePath) {
            imagePath = oldImagePath;

        }

        return fbAdmin
        .auth()
        .verufyIdToken(idToken)
        .then(decodedToken => {
            return bucket.upload(uploadData.filePath, {
                uploadType: 'media',
                destination: imagePath,
                metadata: {
                    metadata: {
                        contentType: uploadData.type,
                        firebaseStorageDownloadToken: id
                    }
                }
            });
        })
        .then(() => {
            return res.status(201).json({
                imageUrl: 
                    'https://firebasestorage.googleapis.com/v0/b/' + 
                    bucket.name + 
                    '/o/' + 
                    encodeURIComponent(imagePath) + 
                    '?alt=media&token' + 
                    id,
                imagePath: imagePath
            });
        })
        .catch(error => {
            return res.status(401).json({ error: 'Unauthorized!' });
        });
    });
    return busboy.end(req.rawBody);
    });
});

, а вот мой полный package.json,

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "@google-cloud/common": "^0.25.3",
    "@google-cloud/paginator": "^0.1.1",
    "@google-cloud/storage": "^1.7.0",
    "busboy": "^0.2.14",
    "cors": "^2.8.4",
    "firebase": "^5.5.3",
    "firebase-admin": "^6.0.0",
    "firebase-functions": "^2.0.5",
    "gcs-resumable-upload": "^0.13.0",
    "split-array-stream": "^2.0.0",
    "uuid": "^3.3.2"
  },
  "private": true
}

, спасибо всем за ваши ответы.Я надеюсь, что мое решение может помочь кому-то

0 голосов
/ 10 октября 2018

Попробуйте это.

  1. Запустите этот код локально, используя

    • firebase functions:shell или
    • firebase serve --only functions

    См. this для получения более подробной информации.

  2. Найдите подробную трассировку стека в firebase-debug.log файле, который будетсгенерировано в вашем каталоге.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...