# Connect to S4 with Node.js

> Connect to Bitiful S4 from Node.js with the AWS SDK for JavaScript v3: complete examples for uploads, multipart uploads, downloads, listing, presigned URLs, extension parameters, and error handling.

Uses the AWS SDK for JavaScript v3. The code below can be placed in a single file and run in order. For browser usage, see [Browser JavaScript](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md).

## Prerequisites

1. [Create a bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/buckets.md) in the console;
2. [Create a sub-user and AccessKey](https://docs.bitiful.com/en/bitiful-s4/handbook/access-keys.md), and [grant the sub-user access to this bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). A new sub-user has no permissions;
3. Put the keys in environment variables instead of writing them in code:

```bash
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"
```

## Install

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

The examples on this page were tested on Node.js 26 and @aws-sdk/client-s3 3.1176.0, using ES modules (file extension `.mjs`, or set `"type": "module"` in `package.json`).

## Connect to S4

```javascript title="s4.mjs"
import { S3Client } from "@aws-sdk/client-s3";

const s3 = new S3Client({
  endpoint: "https://s3.bitiful.net",
  region: "cn-east-1",
  credentials: {
    accessKeyId: process.env.S4_ACCESS_KEY,
    secretAccessKey: process.env.S4_SECRET_KEY,
  },
  // Do not put the checksum in the URL for presigned uploads
  requestChecksumCalculation: "WHEN_REQUIRED",
  responseChecksumValidation: "WHEN_REQUIRED",
});

const Bucket = "my-bucket";
```

> **Note**
>
> Recent SDK versions calculate checksums by default. Without `requestChecksumCalculation: "WHEN_REQUIRED"`, the presigned upload URL includes a checksum parameter for empty content, so keep these two lines.

## Upload files

An object with the same name is overwritten directly. If `ContentType` is left empty, S4 [detects it automatically](https://docs.bitiful.com/en/best-practice/auto-detect-mime.md).

```javascript title="s4.mjs"
import { readFile } from "node:fs/promises";
import { PutObjectCommand } from "@aws-sdk/client-s3";

// Upload a text string
await s3.send(new PutObjectCommand({
  Bucket,
  Key: "docs/hello.txt",
  Body: "你好，S4",
  ContentType: "text/plain; charset=utf-8",
}));

// Upload a local file, setting cache time and custom metadata
await s3.send(new PutObjectCommand({
  Bucket,
  Key: "images/photo.jpg",
  Body: await readFile("photo.jpg"),
  ContentType: "image/jpeg",
  CacheControl: "max-age=86400",
  Metadata: { author: "bitiful" },
}));
```

## Upload large files

Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.

```javascript title="s4.mjs"
import { createReadStream } from "node:fs";
import { Upload } from "@aws-sdk/lib-storage";

const upload = new Upload({
  client: s3,
  params: {
    Bucket,
    Key: "videos/video.mp4",
    Body: createReadStream("video.mp4"),
    ContentType: "video/mp4",
  },
  partSize: 16 * 1024 * 1024, // 16 MiB per part
  queueSize: 4, // 4 parts uploaded at a time
});

upload.on("httpUploadProgress", (p) => console.log(`Uploaded ${p.loaded} bytes`));
await upload.done();
```

## Download files

Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.

```javascript title="s4.mjs"
import { createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { GetObjectCommand } from "@aws-sdk/client-s3";

// Read as a string
const hello = await s3.send(new GetObjectCommand({ Bucket, Key: "docs/hello.txt" }));
console.log(await hello.Body.transformToString());

// Stream to a file
const video = await s3.send(new GetObjectCommand({ Bucket, Key: "videos/video.mp4" }));
await pipeline(video.Body, createWriteStream("video-copy.mp4"));

// Read only the first 1 KiB
const part = await s3.send(new GetObjectCommand({
  Bucket,
  Key: "videos/video.mp4",
  Range: "bytes=0-1023",
}));
console.log(part.ContentRange, (await part.Body.transformToByteArray()).length);
```

## List files

Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. `Delimiter` supports only `/`.

```javascript title="s4.mjs"
import { ListObjectsV2Command, paginateListObjectsV2 } from "@aws-sdk/client-s3";

// List all objects under a prefix, paging automatically
for await (const page of paginateListObjectsV2({ client: s3 }, { Bucket, Prefix: "images/" })) {
  for (const obj of page.Contents ?? []) {
    console.log(obj.Key, obj.Size, obj.LastModified);
  }
}

// List only the top-level directories
const root = await s3.send(new ListObjectsV2Command({ Bucket, Delimiter: "/" }));
for (const p of root.CommonPrefixes ?? []) console.log("Directory", p.Prefix);
```

## Get file information

Retrieve metadata without downloading the content. You can also use this to check whether an object exists.

```javascript title="s4.mjs"
import { HeadObjectCommand } from "@aws-sdk/client-s3";

async function exists(Key) {
  try {
    await s3.send(new HeadObjectCommand({ Bucket, Key }));
    return true;
  } catch (err) {
    if (err.$metadata?.httpStatusCode === 404) return false;
    throw err;
  }
}

const info = await s3.send(new HeadObjectCommand({ Bucket, Key: "images/photo.jpg" }));
console.log(info.ContentType, info.ContentLength, info.ETag, info.Metadata);
console.log(await exists("images/none.jpg"));
```

## Copy and move

Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append `?move=true` to CopySource. It only changes the location without copying data, regardless of file size. See [Move and rename objects](https://docs.bitiful.com/en/bitiful-s4/features/move-object.md).

```javascript title="s4.mjs"
import { CopyObjectCommand } from "@aws-sdk/client-s3";

// The object key in CopySource must be URL-encoded
const encodeKey = (key) => key.split("/").map(encodeURIComponent).join("/");

// Copy
await s3.send(new CopyObjectCommand({
  Bucket,
  Key: "images/photo-copy.jpg",
  CopySource: `${Bucket}/${encodeKey("images/photo.jpg")}`,
}));
```

```javascript title="s4.mjs"
// Move / rename: S4 extension, no data copied
await s3.send(new CopyObjectCommand({
  Bucket,
  Key: "archive/photo.jpg",
  CopySource: `${Bucket}/${encodeKey("images/photo-copy.jpg")}?move=true`,
}));
```

## Delete files

Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.

```javascript title="s4.mjs"
import { DeleteObjectCommand, DeleteObjectsCommand } from "@aws-sdk/client-s3";

// Delete one object
await s3.send(new DeleteObjectCommand({ Bucket, Key: "docs/hello.txt" }));

// Batch delete, up to 1000 objects at a time
const keys = ["images/a.jpg", "images/b.jpg"];
const result = await s3.send(new DeleteObjectsCommand({
  Bucket,
  Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true },
}));
for (const e of result.Errors ?? []) console.log(e.Key, e.Code, e.Message);
```

## Presigned URLs

A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign `Content-Type` for an upload, the client must send exactly the same value.

```javascript title="s4.mjs"
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

// Download URL, valid for 1 hour, with a specified file name
const getUrl = await getSignedUrl(
  s3,
  new GetObjectCommand({
    Bucket,
    Key: "images/photo.jpg",
    ResponseContentDisposition: 'attachment; filename="photo.jpg"',
  }),
  { expiresIn: 3600 },
);
console.log(getUrl);

// Upload URL, valid for 10 minutes; the client sends a PUT to it
const putUrl = await getSignedUrl(
  s3,
  new PutObjectCommand({ Bucket, Key: "uploads/avatar.jpg" }),
  { expiresIn: 600 },
);
console.log(putUrl);
```

## Presigned URLs with extension parameters

Extension parameters such as [CoreIX processing parameters](https://docs.bitiful.com/en/coreix/basic.md), rate limits, and request limits must be added **before signing**. Appending them after signing returns `SignatureDoesNotMatch`.

```javascript title="s4.mjs"
// Generate a presigned URL with S4 extension parameters; they are included in the signature
async function presignWith(command, extra, expiresIn = 3600) {
  command.middlewareStack.add(
    (next) => (args) => {
      Object.assign(args.request.query, extra);
      return next(args);
    },
    { step: "build", name: "addS4Query" },
  );
  return getSignedUrl(s3, command, { expiresIn });
}

const target = { Bucket, Key: "images/photo.jpg" };

// CoreIX: 500 px wide, convert to WebP
console.log(await presignWith(new GetObjectCommand(target), { w: "500", fmt: "webp" }));
// Per-connection rate limit of 1 MiB/s
console.log(await presignWith(new GetObjectCommand(target), { "x-bitiful-limit-rate": "1048576" }));
// At most 3 accesses
console.log(await presignWith(new GetObjectCommand(target), { "x-bitiful-max-requests": "3" }));
// The upload URL can be used only once
console.log(await presignWith(new PutObjectCommand(target), { "x-bitiful-max-requests": "1" }, 600));
```

## Conditional writes

Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See [Conditional requests](https://docs.bitiful.com/en/developer/s3/conditional-requests.md).

```javascript title="s4.mjs"
try {
  // Write only if the object does not exist, to prevent overwriting
  await s3.send(new PutObjectCommand({ Bucket, Key: "locks/job", Body: "me", IfNoneMatch: "*" }));
} catch (err) {
  if (err.name === "PreconditionFailed") console.log("Object already exists");
  else throw err;
}
```

## Handle errors

For the meaning of each error code, see [Error codes and troubleshooting](https://docs.bitiful.com/en/developer/s3/errors.md). Rate limiting returns 429 `TooManyRequest`; catch it and retry with backoff.

```javascript title="s4.mjs"
import { NoSuchKey, S3ServiceException } from "@aws-sdk/client-s3";

try {
  await s3.send(new GetObjectCommand({ Bucket, Key: "not-exists.txt" }));
} catch (err) {
  if (err instanceof NoSuchKey) {
    console.log("Object does not exist");
  } else if (err instanceof S3ServiceException) {
    console.log(err.$metadata.httpStatusCode, err.name, err.message, err.$metadata.requestId);
  } else {
    throw err; // network errors, etc.
  }
}
```

## FAQ

<details>
<summary>How do I use TypeScript</summary>

You can rename the example code to `.ts` directly; the SDK ships with type definitions.

</details>

<details>
<summary>Returns 403 AccessDenied</summary>

The sub-user has no permission on this bucket or directory. See [Sub-user permissions](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). Creating and deleting buckets can only be done in the console.

</details>

<details>
<summary>Returns SignatureDoesNotMatch</summary>

The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the [checklist](https://docs.bitiful.com/en/developer/s3/errors.md).

</details>

<details>
<summary>Download speed is low</summary>

Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a [CDN](https://docs.bitiful.com/en/cdn/intro.md) to serve visitors.

</details>

## Related documentation

[**Presigned URLs and extensions**](https://docs.bitiful.com/en/developer/s3/presigned-url.md)

Full reference for request limits, rate limits, Simul-Transfer, and other parameters.

[**Error codes and troubleshooting**](https://docs.bitiful.com/en/developer/s3/errors.md)

Checklists for 403, SignatureDoesNotMatch, and other issues.

[**S3 API compatibility**](https://docs.bitiful.com/en/developer/s3/compatibility.md)

Support status and differences for each operation.

[**Upload files securely from the client**](https://docs.bitiful.com/en/best-practice/web-uploads.md)

Recommended practices for direct uploads from browsers and apps.
