All Products
Search
Document Center

Object Storage Service:Manage directories (Node.js SDK)

Last Updated:Sep 21, 2026

OSS provides directories that simulate a folder structure, making it easier to organize, locate, and perform bulk operations on large numbers of objects.

Create a directory

The following code shows how to create a directory.

const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region where your bucket is located. For example, use 'oss-cn-hangzhou' for the China (Hangzhou) region.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name.
  bucket: 'examplebucket',
});

async function putBuffer () {
  try {
    // Specify the directory name. The name must end with a forward slash (/).
    const result = await client.put('exampledir/', new Buffer(''));
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

putBuffer();

Delete a directory

Warning

Deleting a directory also deletes all its subdirectories and objects. Proceed with caution.

The following code shows how to delete the log/ directory and all objects in it.

const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region where your bucket is located. For example, for the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'yourregion',
  // This example loads access credentials from environment variables. Before running, ensure that `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name.
  bucket: 'yourbucketname'
});

// Handle a failed request to prevent `promise.all` from being interrupted. Returns the failure reason and the name of the object that failed to be deleted.
async function handleDel(name, options) {
  try {
    await client.delete(name);
  } catch (error) {
    error.failObjectName = name;
    return error;
  }
}

// Delete multiple objects.
async function deletePrefix(prefix) {
  const list = await client.list({
    prefix: prefix,
  });

  list.objects = list.objects || [];
  const result = await Promise.all(list.objects.map((v) => handleDel(v.name)));
  console.log(result);
}
// Delete the directory and all objects in it.
deletePrefix('log/')

References

  • Create a folder

    For more information about the API operation used to create folders, see PutObject.

  • Delete a directory

    • For the complete sample code to delete a directory and all objects in it, see the GitHub example.

    • For more information about the API operation used to delete folders and all their files, see DeleteObject.