Облачное хранилище Google (настройка) NodeJS

#node.js #express #google-cloud-platform #google-cloud-storage

#node.js #экспресс #google-облачная платформа #google-облачное хранилище

Вопрос:

Итак, я смотрю на пример кода из Google и не могу понять, как мне активировать файл конфигурации?

https://cloud.google.com/appengine/docs/flexible/nodejs/using-cloud-storage

Пример кода:

 const {format} = require('util');
const express = require('express');
const Multer = require('multer');
const bodyParser = require('body-parser');

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GOOGLE_CLOUD_PROJECT environment variable. See
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// These environment variables are set automatically on Google App Engine
const {Storage} = require('@google-cloud/storage');

// Instantiate a storage client
const storage = new Storage();

const app = express();
app.set('view engine', 'pug');
app.use(bodyParser.json());

// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
  },
});

// A bucket is a container for objects (files).
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);

// Display a form for uploading files.
app.get('/', (req, res) => {
  res.render('form.pug');
});

// Process the file upload and upload to Google Cloud Storage.
app.post('/upload', multer.single('file'), (req, res, next) => {
  if (!req.file) {
    res.status(400).send('No file uploaded.');
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);
  const blobStream = blob.createWriteStream();

  blobStream.on('error', (err) => {
    next(err);
  });

  blobStream.on('finish', () => {
    // The public URL can be used to directly access the file via HTTP.
    const publicUrl = format(
      `https://storage.googleapis.com/${bucket.name}/${blob.name}`
    );
    res.status(200).send(publicUrl);
  });

  blobStream.end(req.file.buffer);
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl C to quit.');
});


  

Однако, когда вы читаете https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md в нем говорится, что нужно настроить конфигурационный файл и выполнить следующие действия

 {
    "projectId": "grape-spaceship-123",
    "keyFilename": "./PROJECT-XXXXXX.json"
}
  

Имя ключевого файла ссылается на сгенерированный Google JSON.

Но теперь, как мне указать приведенный выше пример кода для его использования?

ПРИМЕЧАНИЕ: Добавление файла конфигурации

 const config = require('./config')
  

Ответ №1:

Я создал хранилище и его работу для меня:

 import { Storage }  from '@google-cloud/storage';//may be you need to use require()
import * as path from 'path';

const storage = new Storage({
  keyFilename: path.join(__dirname, '../********************.json'),
  projectId: '***********Id'
})

const fileBucket = storage.bucket('***********-storage');
  

Хорошее видео об этом: https://www.youtube.com/watch?v=pGSzMfKBV9Q

Комментарии:

1. Спасибо, что очень помогло. Я знаю, это кажется очень простым, но в Документах Google просто нет такого примера — странно, что вы думаете, что у компании размером с Google будет более четкая документация о конфигурациях.

2. вопрос, должно ли это быть -bucket или -storage, поскольку я использовал bucket, и это сработало..