Node.js(Lambda)でS3のファイル存在チェックをする方法

Node.js(Lambda)でS3のファイル存在チェックをする方法

Node.jsでファイル存在確認をするメソッドがないようなので、getObjectメソッドを利用して存在する場合はtrue、存在しない場合はfalseを返すexistFileメソッドを作成します。

JavaScript v2(node.js v12)

const AWS = require('aws-sdk');
const S3 = new AWS.S3({'region':'ap-northeast-1'});

exports.handler = async (event) => {
  const params = {
    'Bucket': 'バケット名',
    'Key': 'hoge/sample.json'
  }
  const data = await existFile(params)
  console.log(data) // 出力
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda'),
  }
  return response
}

async function existFile(params){
  let bool = true
  await S3.getObject(params).promise().catch(e=>{
    bool = false
  })
  return bool
}

getObjectメソッドでファイルが存在しない場合はcatchされますので、await-catch句でfalseにします。

JavaScript v3(node.js v18)

import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'

const client = new S3Client({
  region: 'ap-northeast-1'
})
export const handler = async(event) => {
  const params = {
    'Bucket': 'バケット名',
    'Key': 'hoge/sample.json'
  }
  const data = await existFile(params)
  console.log(data) // 出力
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda'),
  };
  return response;
}

async function existFile(params){
  let bool = true
  const command = new GetObjectCommand(params)
  const data = await client.send(command).catch(e=>{
    bool = false
  })
  return bool
}

Java

JavaではdoesObjectExistメソッドが用意されているようです。

JavaでS3のオブジェクトが存在するしないを確認する方法

コメント

タイトルとURLをコピーしました