Search code examples
node.jsgoogle-cloud-storagemulter

How to properly initialize google cloud storage and bucket and/or intialize Multer


I am not quite sure how to initialize Multer and google cloud storage bucket, as I get errors when doing so. I am using an express node app with a package.json and a yarn.lock instead of package-lock.json with a goal of uploading images files to it, and with multer and google cloud storage saving the images.

The only documentation I could find is the cloud-storage client documentation(I think this might be an issue, as this is on the server in node? Or more likely I not and I am just confused), that gives me an error when I attempt it. I have also attempted some other stack overflow intialization examples, such as the the code below, that resulted in

error: Storage is not a function

And attempting to put "new" before it gives "storage is not a constructor"

These errors are for both Multer and Cloud storage.

const express = require('express');

const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
  console.log('server started');
});

var fs = require('fs');

var router = express.Router();

const Multer = require('multer');
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
  }
});
const Storage = require('@google-cloud/storage');

const storage = Storage({
  keyFilename: 'pathtothing',
  projectId: 'theID'
});

My best guess is that this is outdated, would anyone know how to properly initialize either of these or could show documentation that is relevant. Thanks!


Solution

  • The @google-cloud/storage has a detailed quickstart section and the import statement should be:

    const { Storage } = require('@google-cloud/storage'); // add the { }
    
    // Storage is a constructor so add 'new'
    const storage = new Storage({
      keyFilename: 'pathtothing',
      projectId: 'theID'
    });
    

    If you use the default import then it should be:

    const Storage = require('@google-cloud/storage'); 
    
    // Storage is a constructor so add 'new'
    const storage = new Storage.Storage({
      keyFilename: 'pathtothing',
      projectId: 'theID'
    });