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メソッドが用意されているようです。

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^


コメント