{{announcement.body}}
{{announcement.title}}

How To: Set and Retrieve Metadata of an S3 Object

DZone 's Guide to

How To: Set and Retrieve Metadata of an S3 Object

In this article, we discuss how to set and retrieve system and user-defined metadata of an s3 object with Node.js in AWS.

· Web Dev Zone ·
Free Resource

In the article we will see how to upload the metadata of an object while uploading to S3 programatically.

I will be using Node.js to demonstrate the same.

Before jumping to that let’s see what is metadata and it’s use case

We have 2 types of metadata

  1. System Metadata    E.g. Date, Content-Length
  2. User defined metadata

While we upload the object, we can add custom metadata about the object along that as a key-value pair

 

Note: All user-defined metadata keys in lowercase

 

Let’s say we are having a platform where contents are added by multiple organization. In this scenario adding OrganizationID as one of the metadata will be handy.

Following code helps you to upload an object to s3 along it’s metadata.

JavaScript




x
43


 
1
var AWS = require('aws-sdk')
2
var credentials = require('./cred');
3
var s3 = new AWS.S3({accessKeyIdcredentials.accesskey,
4
    secretAccessKeycredentials.secretkey,region:credentials.region});
5
var fs = require('fs');
6
 
          
7
fs.readFile('file2.txt'function (errdata) {
8
    if (err) { throw err; }
9
    var base64data = new Buffer(data'binary');
10
    s3.putObject({
11
        Bucket'uploadmetatest',
12
        Key'vijaykishan.txt',
13
        Metadata: {OrgID'TEKKIHUT'PROFILE'HD'},
14
        Bodybase64data,
15
        ACL'public-read'
16
    }, function (resp) {
17
        console.log('Successfully uploaded package.');
18
    });
19
});


 

Let’s see how to retrieve the metadata of an uploaded object using node.js.

Following code helps you to retrieve the metadata of an object uploaded to s3.

JavaScript
xxxxxxxxxx
1
25
1
var params = {
2
    Bucket"uploadmetatest",
3
    Key"file2.txt"
4
};
5
s3.headObject(paramsfunction (errdata) {    if (errconsole.log(errerr.stack); // an error occurred
6
    else {
7
        console.log(data.Metadata['orgid']);
8
        console.log(data.Metadata['profile']);
9
   }       
10
});

 

Note

The PUT request header is limited to 8 KB in size. Within the PUT request header, the user-defined metadata is limited to 2 KB in size. The size of user-defined metadata is measured by taking the sum of the number of bytes in the UTF-8 encoding of each key and value.

 

Hope this helps

Topics:
s3 ,metadata ,node.js ,web dev ,aws ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}