[Node.js] Detect a missing object error from AWS.S3.getObject (AWS SDK for JavaScript v2)

Created on November 28, 2026

When you pass a missing object's key to AWS.S3.getObject, the request can fail. Catch the error with try...catch and inspect its code property to identify the error. This example logs a message and returns when it receives the NoSuchKey error for a missing object.

const AWS = require("aws-sdk");

async function main() {
  const s3 = new AWS.S3({
    region: "ap-northeast-1",
  });

  const result = null;
  try {
    result = await s3
      .getObject({
        Bucket: "dummy.s3.example.com",
        Key: "dummy_files/dummy_file_does_not_exist.txt",
      })
      .promise();
  } catch (e) {
    if (e.code === "NoSuchKey") {
      console.log("the file does not exist");
      return;
    }
  }

  console.log(result.Body.toString());
}

main();

The script produces the following output.

the file does not exist
Node.js AWS