Check whether a file exists (Browser.js SDK)
This topic describes how to check whether a specified file (Object) exists.
Usage notes
-
When you use packaging tools such as Webpack and Browserify, install OSS SDK for Browser.js by running the npm install ali-oss command.
-
If you want to access an OSS bucket from a browser but no CORS rules are configured for the bucket, the browser rejects the request. Therefore, you must configure CORS rules for a bucket if you want to access the bucket from a browser. For more information, see Installation.
-
In most cases, OSS SDK for Browser.js is used in browsers. To prevent your AccessKey pair from being exposed, we recommend that you use temporary access credentials obtained from Security Token Service (STS) to access OSS.
The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information about how to obtain temporary access credentials, see Use STS for temporary access authorization.
Sample code
The following code provides an example of how to check whether the exampleobject.txt file exists in the examplebucket bucket.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.17.1.min.js"></script>
</head>
<body>
<script>
const client = new OSS({
// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from STS.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token (SecurityToken) obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name.
bucket: 'examplebucket'
});
async function isExistObject(name, options = {}) {
try {
await client.head(name, options);
console.log("The file exists.");
} catch (error) {
if (error.code === "NoSuchKey") {
console.log("The file does not exist.");
}
}
}
// Check whether the specified object exists.
// Specify the full path of the object. Do not include the bucket name. For example, exampleobject.txt.
const name = "exampleobject.txt";
isExistObject(name);
</script>
</body>
</html>