A
A
Alexander2019-11-12 12:59:15
API
Alexander, 2019-11-12 12:59:15

How to interact with Yandex Object Storage via JS?

For example, Amazon has its own SDK for AWS ( https://aws.amazon.com/ru/sdk-for-browser/)
Yandex seems to be compatible with AWS, but I did not find a JS SDK with them.
Perhaps I don't understand something. I just started looking into this service.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Borigaldi, 2021-02-02
@Borigaldi

Something like this code for Node.js. Docks are here

const AWS = require('aws-sdk');
require('dotenv').config(); // для получения переменных из окружения Node.js

class YandexCloud {

  constructor () {
    this.aws = new AWS.S3({
      endpoint: 'https://storage.yandexcloud.net', 
      accessKeyId: process.env.YA_STORAGE_ACCESS_KEY, // берем ключ из переменной окружения
      secretAccessKey: process.env.YA_STORAGE_SECRET_KEY, // берем секрет из переменной окружения
      region: 'ru-central1',
      httpOptions: {
        timeout: 10000,
        connectTimeout: 10000
      },
    });
  }

  upload = async ({file,path,fileName}) =>  {
    try {
      const params = {
        Bucket: 'название', // название созданного bucket
        Key: `${path}/${fileName}`, // путь и название файла в облаке (path без слэша впереди)
        Body: file, // сам файл
        ContentType: 'text/plain', // тип файла
      }
      const result = await new Promise(function(resolve, reject) {
        this.aws.upload(params, function(err, data) {
          if (err) return reject(err);
          return resolve(data);
        });
      });
      return result;
    } catch (e) {
      console.error(e);
    }
  }
}

const YaCloud = new YandexCloud();
YaCloud.upload({
  file: '', // файл
  path: 'путь/в/облаке',
  fileName: 'файл.txt',
})

A
akot777, 2022-03-13
@akot777

Thanks Borigaldi for the answer... But)))
If you don't want to install the full SDK (70 mb), you can use only the @aws-sdk/client-s3 module (4 mb)

const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');

And the Credentials should be specified like this:
credentials: {
      accessKeyId: accessKeyId, // берем ключ из переменной окружения
      secretAccessKey: secretAccessKey, // берем секрет из переменной окружения
    },

And another method .send(new PutObjectCommand(params)) instead of .upload():
const result = await new Promise(function(resolve, reject) {
        aws.send(new PutObjectCommand(params)).then(
          (data) => {
            console.log(data)
            resolve(data)
          },
          (error) => {
            console.log(error)
            reject(error)
          }
        );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question