Подтвердить что ты не робот

Ошибка ESLint при попытке развертывания функций firebase

Я попытался развернуть функции Firebase, но она продолжает сбой из-за некоторых проблем с ESLint. Я также пытался найти ответ, но все, что я вижу, для меня все греческое.

Я также наткнулся на этот и этот ответ, но, похоже, они не применимы к моему сценарию.

Моя функция

// // 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!");
// });


//import firebase functions modules
const functions = require("firebase-functions");
//import admin module
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

// Listens for new messages added to messages/:pushId
exports.pushNotification = functions.database.ref("/Message").onWrite( event => {
    //  Grab the current value of what was written to the Realtime Database.
    var valueObject = event.data.val();
    // Log the event
    console.log("Push notification event triggered for " + valueObject.title);

    //if(valueObject.title != null) {
      //valueObject.photoUrl= "Sent you a photo!";
   // }

  // Create a notification
    const payload = {
        data: {
            body:valueObject.body,
            imgUrl: valueObject.imgUrl,
            postUrl: valueObject.postUrl,
            title: valueObject.title
        },
    };

  //Create an options object that contains the time to live for the notification and the priority
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };


    return admin.messaging().sendToTopic("Posts", payload, options);
});

Журнал

0 info it worked if it ends with ok
1 verbose cli [ '/home/xoxo/.nvm/versions/node/v9.5.0/bin/node',
1 verbose cli   '/home/xoxo/.nvm/versions/node/v9.5.0/bin/npm',
1 verbose cli   '--prefix',
1 verbose cli   '/home/xoxo/Android/Projects/FirebaseFunctions/functions',
1 verbose cli   'run',
1 verbose cli   'lint' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prelint', 'lint', 'postlint' ]
5 info lifecycle [email protected]~prelint: [email protected]
6 info lifecycle [email protected]~lint: [email protected]
7 verbose lifecycle [email protected]~lint: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~lint: PATH: /home/xoxo/.nvm/versions/node/v9.5.0/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/xoxo/Android/Projects/FirebaseFunctions/functions/node_modules/.bin:/home/xoxo/.nvm/versions/node/v9.5.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
9 verbose lifecycle [email protected]~lint: CWD: /home/xoxo/Android/Projects/FirebaseFunctions/functions
10 silly lifecycle [email protected]~lint: Args: [ '-c', 'eslint .' ]
11 info lifecycle [email protected]~lint: Failed to exec lint script
12 verbose stack Error: [email protected] lint: 'eslint .'
12 verbose stack spawn ENOENT
12 verbose stack     at ChildProcess.<anonymous> (/home/xoxo/.nvm/versions/node/v9.5.0/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:48:18)
12 verbose stack     at ChildProcess.emit (events.js:160:13)
12 verbose stack     at maybeClose (internal/child_process.js:943:16)
12 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
13 verbose pkgid [email protected]
14 verbose cwd /home/xoxo/Android/Projects/FirebaseFunctions
15 verbose Linux 4.13.0-32-generic
16 verbose argv "/home/xoxo/.nvm/versions/node/v9.5.0/bin/node" "/home/xoxo/.nvm/versions/node/v9.5.0/bin/npm" "--prefix" "/home/xoxo/Android/Projects/FirebaseFunctions/functions" "run" "lint"
17 verbose node v9.5.0
18 verbose npm  v5.6.0
19 error file sh
20 error code ELIFECYCLE
21 error errno ENOENT
22 error syscall spawn
23 error [email protected] lint: 'eslint .'
23 error spawn ENOENT
24 error Failed at the [email protected] lint script.
24 error This is probably not a problem with npm. There is likely additional logging output above.
25 verbose exit [ 1, true ]

Консольный выход

[email protected]:~/Android/Projects/FirebaseFunctions$ firebase deploy

=== Deploying to 'testproject-a1bda'...

i  deploying functions
Running command: npm --prefix $RESOURCE_DIR run lint

> [email protected] lint /home/xoxo/Android/Projects/FirebaseFunctions/functions
> eslint .

sh: 1: eslint: not found
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! [email protected] lint: 'eslint .'
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the [email protected] lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/xoxo/.npm/_logs/2018-02-03T22_35_55_608Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

Package.js

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "./node_modules/.bin/eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "firebase-admin": "~5.8.1",
    "firebase-functions": "^0.8.1"
  },
  "devDependencies": {
    "eslint": "^4.12.0",
    "eslint-plugin-promise": "^3.6.0"
  },
  "private": true
}

enter image description here

Пожалуйста, что я делаю не так?

4b9b3361

Ответ 1

Единственный способ представить, что ваш проект попал в это состояние, - это если вы отказались разрешить npm устанавливать зависимости во время создания проекта. Поэтому, когда вы спрашиваете об этом:

? Вы хотите установить зависимости с npm сейчас?

Возможно, вы ответили "Нет". Это предотвратит установку пакета eslint, и вы увидите эту ошибку.

В противном случае вы, возможно, удалили установленный пакет node_modules под node_modules. Вы можете запустить npm install из папки functions чтобы воссоздать все, что необходимо в node_modules.

Ответ 2

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

let params = {...};
var firestore = admin.firestore();
var dbRef = firestore.collection('your-collection-name');

dbRef.add(params)
     .then((docRef) => {
       console.log("doc added with ID ", docRef.id);

       return null
     })
     .catch((err) => {
       console.error("Error in adding document ", err);
     });

Ответ 3

Была такая же проблема Я переустановил npm

npm install npm -g

затем перезапускает функции Firebase (нужно перезаписать все файлы и обязательно установить EsLine для отладки и установить все зависимости) да нажмите Y для любого запроса

Firebase init functions

и все работало очень хорошо после повторного развертывания

Firebase deploy

Ответ 4

У меня появилась похожая ошибка. Я обнаружил, что мой каталог, в котором находился проект firebase, назывался firebase/database. Я удалил/и сделал каталог с именем firebase-database. Надеюсь, это кому-нибудь поможет.

Ответ 5

просто - из корня вашего проекта Firebase перейдите в папку с вашими функциями следующим образом:

cd functions

а затем установить npm.

после завершения установки, c