10

My upload.js file contains the following code:

module.exports = {

    up: function () {
        const storage = require('@google-cloud/storage');
        const fs = require('fs');
        const gcs = storage({
            projectId: 'MY_PROJECT_ID',
            keyFilename: './service-account.json'
        });
        var bucket = gcs.bucket('MY_BUCKET');

        bucket.upload('picture.jpg', function(err, file) {
            if (err) throw new Error(err);
        });
    },
}

It works through the terminal but how do I call it on form submission button click or just from different file ?

When I try it gives me:

Cannot read property 'prototype' of undefined

I'm quite new to NodeJs and I don't really know what to do.
Google documentation doesn't help me at all unfortunately :/

Stphane
  • 3,368
  • 5
  • 32
  • 47
Pavel Havlík
  • 101
  • 1
  • 1
  • 3
  • Are you getting this error in browser console? Or if it is a different function, can you share the code from there? – Shriram Manoharan Feb 22 '18 at 04:02
  • Related if there is no physical file [How do I upload a base64 encoded image (string) directly to a Google Cloud Storage bucket using Node.js?](https://stackoverflow.com/questions/42879012/how-do-i-upload-a-base64-encoded-image-string-directly-to-a-google-cloud-stora) – Liam Oct 05 '22 at 14:04

2 Answers2

8

I would recommend moving your requires to the first line.

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

module.exports = {
    up: function () {
        const gcs = storage({
            projectId: 'MY_PROJECT_ID',
            keyFilename: './service-account.json'
        });
        const bucket = gcs.bucket('MY_BUCKET');
        bucket.upload('picture.jpg', function(err, file) {
            if (err) throw new Error(err);
        });
    },
}

I would also console.log(storage) and confirm it is defined.

Dan Rasmuson
  • 5,705
  • 5
  • 29
  • 45
4
const { Storage } = require('@google-cloud/storage');

const up = () => {
    const gcs = new Storage({
        projectId: 'xxxxxxxxx',
        keyFilename: './service-account.json'
    });
    const bucket = gcs.bucket('xxxxxxxxxx');
    bucket.upload('./test-rev.mkv', function (err, file) {
        if (err) throw new Error(err);
    });
}
Tarang
  • 75,157
  • 39
  • 215
  • 276