2

I'm trying to create and image on the Google Firebase server with node-canvas and store it in Firebase Storage.

const functions = require('firebase-functions');
const admin = require('firebase-admin');

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

const path = require('path');
const Canvas = require('canvas-prebuilt');

const env = require('dotenv').config();

try {admin.initializeApp(functions.config().firebase);} catch(e) {}

//Trigger on creation of a new post
exports.default = functions.database.ref('/posts/{postId}').onCreate(event => {

    //Get the postID
    const postId = event.params.postId;

    console.log('We have a new post ' + postId);

    //Get data from the postid
    return admin.database().ref('/posts/' + postId).once('value').then(function(snapshot) {
        const text = snapshot.val().text;

        const canvas = new Canvas(1024, 512);
        const ctx = canvas.getContext('2d');

        //Draw Background
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, 1024 , 512);

        //Draw Text
        ctx.font = 'bold 66px Arial';
        ctx.textAlign = 'center';
        ctx.fillStyle = '#fff';
        ctx.fillText(text, 120, 256, 784);

        // Use the postID to name the file Ex : -L1rVJUAtSbc_FampT0D.png
        var filename = postId + '.png';

        // Create the file metadata
        var metadata = {
          contentType: 'image/png'
        };

        const bucket = gcs.bucket('images');
        const filePath = 'images/' + filename;

        return canvas.toDataURL('image/png', function(err, png){

            //Save on Firebase Storage
            return bucket.upload(png, {
            destination: filePath,
            metadata: metadata
            }).then(() => {

                console.log('Image uploaded to Storage at ', filePath);

            });

        });

    });

});

But, when I try to save it with toDataURL I get this error :

    ENAMETOOLONG: name too long, stat 'data:image/png;base64,iVBORw0 ...'

And when I try with toBuffer I get this one :

    TypeError: Path must be a string. Received 
        at assertPath (path.js:7:11)
        at Object.basename (path.js:1362:5)
        at Bucket.upload (/user_code/node_modules/@google-cloud/storage/src/bucket.js:2259:43)
        at /user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:777:22
        at Bucket.wrapper [as upload] (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:761:12)
        at /user_code/sendTweet.js:107:21

I also try toBlob but the function doesn't exist server side with node-canvas.

Anyone know how I should save the image server side before transfer it to Firebase Storage?

Thanks!

Phil
  • 63
  • 1
  • 5

0 Answers0