---
name: azion-upload-a-folder-to-a-bucket-from-node-js
description: >-
  Upload every file of a local folder to an Object Storage bucket, keyed by its path and typed by its extension, from Node.js with @aziontech/storage.
---

# Upload a folder to a bucket from Node.js

You can upload every file of a local folder to an [Object Storage](/en/documentation/platform/object-storage/) bucket from a Node.js script. The script uses the `@aziontech/storage` package of [Azion Lib](/en/documentation/devtools/azion-lib/). Each object takes the file's path inside the folder as its key. The script picks the object's content type from the file extension.

---

## Prerequisites

- Node.js 24.21.0 or later, and npm. The script is an ES module that reads the folder with the `recursive` option of `readdir` and the `parentPath` of each entry.
- A personal token. To create one, refer to [Manage personal tokens](/en/documentation/guides/platform/account-and-billing/personal-tokens/).
- A bucket. To create one from Node.js, refer to [Create a bucket](/en/documentation/devtools/azion-lib/quickstart/#create-a-bucket). The examples use a bucket named `site-assets-4940`.
- A folder to upload. The examples use a `public` folder with three files: `index.html`, `css/site.css`, and `img/logo.svg`.

---

## Install the package

The script imports `@aziontech/storage` from the `node_modules` directory of its project.

In the directory that holds the folder to upload, create the project and install the package:

```bash
npm init -y
npm install @aziontech/storage
```

npm prints the new `package.json`, and the install ends with:

```text
added 2 packages, and audited 3 packages in 2s

found 0 vulnerabilities
```

The project has `@aziontech/storage` in its `package.json` dependencies.

---

## Write the upload script

The script first reads the bucket with [`getBucket`](/en/documentation/devtools/azion-lib/storage/#get-a-bucket), which looks it up by its exact name. When the bucket does not exist, the script stops. For each file of the folder, the [`createObject`](/en/documentation/devtools/azion-lib/storage/#create-an-object) function then creates an object. Its key is the file's path inside the folder, with `/` between the parts, such as `css/site.css`.

`createObject` stores the content type you pass in `params.content_type`, and Object Storage returns it in the `Content-Type` header of the object. Without one, `createObject` sends `application/octet-stream`, and the object keeps that type. Object Storage [detects a type](/en/documentation/platform/object-storage/buckets-and-objects/#content-type) only for an upload that carries no `Content-Type` header. The script picks the content type from the file extension.

The [`getObjects`](/en/documentation/devtools/azion-lib/storage/#get-objects) function then lists the objects of the bucket. The script counts how many of its uploaded keys are in that list. Objects the bucket held before therefore do not change the count. Each function reads your personal token from the `AZION_TOKEN` environment variable.

`getObjects` asks for at most 10,000 objects by default. In a larger bucket, an uploaded key can be missing from the list.

The script takes the folder and the bucket name as its two arguments. Create an `upload.mjs` file:

```javascript
import { readdir, readFile } from 'node:fs/promises';
import { extname, join, relative, sep } from 'node:path';
import { createObject, getBucket, getObjects } from '@aziontech/storage';

const [folder, bucket] = process.argv.slice(2);
const contentTypes = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.js': 'text/javascript',
  '.json': 'application/json',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.txt': 'text/plain',
};

const { error: bucketError } = await getBucket({ name: bucket });
if (bucketError) {
  console.error(`Upload failed: ${bucketError.message}`);
  process.exit(1);
}

const uploaded = [];
const entries = await readdir(folder, { recursive: true, withFileTypes: true });
for (const entry of entries.filter((item) => item.isFile())) {
  const file = join(entry.parentPath, entry.name);
  const key = relative(folder, file).split(sep).join('/');
  const contentType = contentTypes[extname(file)] ?? 'application/octet-stream';
  const { error } = await createObject({
    bucket,
    key,
    content: await readFile(file),
    params: { content_type: contentType },
  });
  if (error) {
    console.error(`Upload failed for ${key}: ${error.message}`);
    process.exit(1);
  }
  uploaded.push(key);
  console.log(`Uploaded ${key} (${contentType})`);
}

const { data, error: listError } = await getObjects({ bucket });
if (listError) {
  console.error(`Check failed: ${listError.message}`);
  process.exit(1);
}
const stored = new Set(data.objects.map((object) => object.key));
const confirmed = uploaded.filter((key) => stored.has(key)).length;
console.log(`${confirmed} of ${uploaded.length} files are in ${bucket}`);
if (confirmed !== uploaded.length) process.exit(1);
```

The script prints the error or the count and exits with code `1` when:

- The bucket does not exist.
- An upload fails.
- An uploaded key is missing from the list.

To upload another file type with its content type, add its extension to `contentTypes`.

The script uploads every file of the folder, hidden files such as `.DS_Store` included. Remove the files you do not want to publish before you run it.

---

## Upload the folder

The script uploads the files one at a time and stops at the first upload that fails.

To upload the folder:

1. In the terminal where you run the script, store your personal token in the `AZION_TOKEN` variable. Replace `[TOKEN VALUE]` with your token:

   ```bash
   export AZION_TOKEN=[TOKEN VALUE]
   ```

   Every script you start from this terminal reads the token, until the terminal closes.

2. Run the script with the folder and the name of your bucket:

   ```bash
   node upload.mjs public site-assets-4940
   ```

   ```text
   Uploaded index.html (text/html)
   Uploaded img/logo.svg (image/svg+xml)
   Uploaded css/site.css (text/css)
   3 of 3 files are in site-assets-4940
   ```

3. (Optional) Run the script again after you change a file. An upload to an existing key replaces the object, so the count stays the same:

   ```bash
   node upload.mjs public site-assets-4940
   ```

   ```text
   Uploaded index.html (text/html)
   Uploaded img/logo.svg (image/svg+xml)
   Uploaded css/site.css (text/css)
   3 of 3 files are in site-assets-4940
   ```

The bucket holds one object per file of the folder, each with its content type.

When no bucket has the name you passed, such as `site-assets`, the script prints `Upload failed: The specified bucket does not exist.` and uploads nothing.

---

## Next steps

- [Azion Lib Storage](/en/documentation/devtools/azion-lib/storage.md): Every function of @aziontech/storage, its parameters, and its response envelope.
- [Object Storage](/en/documentation/platform/object-storage.md): How buckets and objects work, and how a request reaches an object.
