Published on

How to check if File Exists in AWS S3 in Nodejs

Authors

Here's how to check if a file exists in AWS S3 in Node.js.

Dependencies

We need to install the package if it's not available already.

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

const config = {
    region: process.env.AWS_DEFAULT_REGION || 'us-east-1',
    credentials: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    },
};
const bucketName = 'YourBucketName';

async function fileExists(filePath) {
    const command = new HeadObjectCommand({
        Bucket: bucketName,
        Key: filePath,
    });
    const s3Client = new S3Client(config);

    try {
        await s3Client.send(command);
        console.log(`File exists: ${filePath}`);
        return { exists: true, error: null };
    } catch (error) {
        if (error.name === 'NotFound') {
            console.log(`File does not exist: ${filePath}`);
            return { exists: false, error: null };
        }
        console.error(`Error checking file existence: ${error}`);
        return { exists: false, error };
    }
}

const filePath = 'path/to/file.pdf'; 
const fileExistsResult = await fileExists(filePath);
console.log(fileExistsResult); // true or false

With this approach we're checking whether the file exists or not without downloading it.

Happy filtering files!