# Basic Command

## คำสั่งพื้นฐานสำหรับการใช้งานเบื้องต้น

* [ListBucketsCommand](#1-listbucketscommand)
* [PutObjectsCommand](#2-putobjectscommand)
* [ListObjectsCommand](#3-listobjectscommand)
* [DeleteObjectCommand](#4-deleteobjectcommand)
* [CopyObjectCommand](#5-copyobjectcommand)
* [GetObjectCommand](#6-getobjectcommand)
* [getSignedUrl](#7-getsignedurl)

## Prerequisite

* ต้องมี bucket สร้างเอาไว้แล้ว ([ขั้นตอนในการสร้าง bucket](/ncs-documents/~/changes/U2SVceQUXXCaek3t7CoE/object-storage/create-an-object-storage-bucket.md))
* มีการสร้าง subuser และ ให้สิทการเข้าถึง bucket เอาไว้แล้ว ([ขั้นตอนการสร้าง subuser และ access key](https://docs-epc.gitbook.io/ncs-documents/~/changes/U2SVceQUXXCaek3t7CoE/object-storage/create-object-storage-sub-user))

## 1) ListBucketsCommand

### สำหรับการเรียกดูรายชื่อ Buckets ภายใน project

การเรียกใช้ ListBucketsCommand ไม่จำเป็นต้องใส่ parameter ใดๆ

```javascript
import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const input = { }
const command = new ListBucketsCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

```json
{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx0000000000000007f36ae-006542153a-b6569ee-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  Buckets: [
      Name: 's3-client-buckets',
      CreationDate: 2023-11-01T08:53:55.139Z
    }
  ],
  Owner: {
    DisplayName: 'DevOps-Prototype',
    ID: 'xxx'
  }
}
```

## 2) PutObjectsCommand

### สำหรับการ upload ข้อมูลเข้าไปยัง Buckets

### parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Body (ข้อมูลที่ต้องการอัพโหลด)
* Key (ชื่อของไฟล์ที่อัพโหลดไปยัง Bucket)

ตัวอย่างการใช้งาน PutObjectsCommand โดยมี package fs สำหรับใช้ในการอ่านไฟล์

```javascript
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import * as fs from 'fs';

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const source = 'path/to/file/file2upload.jpg';
const dest = 'uploadedfile.jpg';
const fileContent = fs.readFileSync(source);
const input = {
    Bucket: ncs_bucket,
    Body: fileContent,
    Key: dest
}
const command = new PutObjectCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

```json
{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx00000000000000035f84a-0065485672-b8c3f38-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  ETag: '"16de86869221ac1c9c66b9397d9845a7"'
}
```

## 3) ListObjectsCommand

สำหรับการเรียกดู Objects ภายใน Bucket

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket ที่ต้องการเรียกดู)

```javascript
import { S3Client, ListObjectsCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const input = {
    Bucket: ncs_bucket
}
const command = new ListObjectsCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

<pre class="language-javascript"><code class="lang-javascript">{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx000000000000000371e77-0065485938-b8c3f38-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
<strong>  },
</strong>  Contents: [
    {
      Key: 'uploadedfile.jpg',
      LastModified: 2023-11-06T03:10:44.618Z,
      ETag: '"16de86869221ac1c9c66b9397d9845a7"',
      Size: 7156660,
      StorageClass: 'STANDARD',
      Owner: [Object]
    }
  ],
  IsTruncated: false,
  Marker: '',
  MaxKeys: 1000,
  Name: 's3-client-buckets',
  Prefix: ''
}
</code></pre>

## 4) DeleteObjectCommand

สำหรับการลบ Objects ภายใน Bucket

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Key (ชื่อของไฟล์ที่ต้องการลบ)

```javascript
import { S3Client, DeleteObjectCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials,
});

const input = {
    Bucket: ncs_bucket,
    Key: "fileons3/file1.jpg"
}
const command = new DeleteObjectCommand(input);

try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

```json
{
  '$metadata': {
    httpStatusCode: 204,
    requestId: 'tx000000000000000378393-0065485a1e-b8c3f0e-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  }
}
```

## 5) CopyObjectCommand

สำหรับการ Copy Object ไปยัง Bucket อื่น หรือ path ใหม่บน Bucket

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket ปลายทาง)
* CopySource (ข้อมูลที้ต้องการทำซ้ำ โดยมี format คือ /{source bucket name}/{source file})
* Key (ไฟล์ปลายทางจากการทำซ้ำ)

\*\* สำหรับ Credentials ที่ใช้งานนั้น จะต้องมีสิท read จาก Bucket ต้นทาง และ สิท write จาก Bucket ปลายทาง

<pre class="language-javascript"><code class="lang-javascript">import { S3Client, CopyObjectCommand } from "@aws-sdk/client-s3";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials,
    forcePathStyle: false
});

const input = {
    Bucket: ncs_bucket,
    CopySource: "/s3-client-buckets/source.file",
    Key: "target.file"
}

const command = new CopyObjectCommand(input);
<strong>
</strong>try {
    const response = await client.send(command);
    console.log(response);
} catch (error) {
    console.log(error);
}
</code></pre>

Result

<pre class="language-json"><code class="lang-json">{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'tx0000000000000003f747c-00654b118d-b947ae8-NCP-BKK',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  CopyObjectResult: {
    ETag: '16de86869221ac1c9c66b9397d9845a7',
    LastModified: 2023-11-08T04:41:49.846Z
  }
<strong>}
</strong></code></pre>

## 6) GetObjectCommand

สำหรับเรียกดูรายชื่อ Object บน Buckets

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Key (ชื่อไฟล์ที่ต้องการ)

```javascript
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import * as fs from 'fs';

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const input = { 
    Bucket: ncs_bucket,
    Key: 'ubuntu.jpeg'
}

const command = new GetObjectCommand(input);
try {
    const response = await client.send(command);
    const inputStream = response.Body;
    const downloadPath = 'ubuntu.jpeg';
    const outputStream = fs.createWriteStream(downloadPath);
    inputStream.pipe(outputStream);
    outputStream.on('finish', () => {
      console.log(`downloaded the file successfully`);
    });
} catch (error) {
    console.log(error);
}
```

<figure><img src="/files/AplGWisayXyVNX7mEUNW" alt=""><figcaption></figcaption></figure>

## 7) getSignedUrl

การสร้าง url ให้ object สำหรับการเปิดใช้งานเฉพาะ object แบบ public ชั่วคราว

## parameter ที่จำเป็นสำหรับการใช้งาน

* Bucket (ชื่อของ Bucket)
* Key (ไฟล์ข้อมูลที่ต้องการ)
* expiresIn (ระยะเวลา(นาที)ที่ url จะสามารถใช้งานได้)

\*\*ต้องทำการ install package ที่ใช้สำหรับการสร้าง presigned url เพิ่มเติม

```bash
npm install @aws-sdk/s3-request-presigner
```

```javascript
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const client = new S3Client({
    region: ncs_region,
    endpoint: ncs_endpoint,
    credentials: ncs_credentials
});

const input = { 
    Bucket: ncs_bucket,
    Key: 'hello-world.jpeg'
}

const command = new GetObjectCommand(input);

try {
    const response = await getSignedUrl(client, command, { expiresIn: 3600 });
		console.log(response);
} catch (error) {
    console.log(error);
}
```

Result

result ที่ได้ จะเป็น url สำหรับการเปิดดูข้อมูล

{% hint style="info" %}
อ้างอิง

<https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/>
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs-epc.gitbook.io/ncs-documents/~/changes/U2SVceQUXXCaek3t7CoE/object-storage/access-s3-buckets-with-aws-s3-client-sdk/basic-command.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
