DEV Community

Cover image for How to check if file exists in S3 bucket using AWS SDK for JavaScript
Yutaro Shimamura
Yutaro Shimamura

Posted on

How to check if file exists in S3 bucket using AWS SDK for JavaScript

Prerequisites

  • "@aws-sdk/client-s3": "^3.38.0" installed
  • You have a file named test.txt in your bucket root
  • Necessary bucket policy and IAM policy are configured

Use HeadObjectCommand to get metadata

There may be better ways, but below is an example just to get metadata of a file stored in S3 bucket.
It's more efficient than getting actual object if you just want to know the file existence.

import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"

// some codes...

const config = {}
const input = {
    Bucket: 'your-bucket',
    Key: 'test.txt'
}
const client = new S3Client(config)
const command = new HeadObjectCommand(input)
const response = await client.send(command)
console.log(response)
Enter fullscreen mode Exit fullscreen mode

response

If you receive status code 200, you're all set.
You will get Not Found error with status code 404 if file does not exist.

{
  '$metadata': {
    httpStatusCode: 200,
    ...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)