Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change file's metadata in Google Cloud Storage with Node.js

My image's (which is hosted in Google Cloud Storage) metadata has the property named downloaded, if the image has been downloaded, the value inside the downloaded key will be changed from 0 to 1.

The code in https://cloud.google.com/storage/docs/viewing-editing-metadata#storage-view-object-metadata-nodejs shows how to view the metadatas but didn't really cover how to change the metadata.

Is it possible to do so?

like image 453
Andre Christoga Pramaditya Avatar asked Oct 19 '25 05:10

Andre Christoga Pramaditya


1 Answers

Yes, it is possible.

The way to do it is by using the File.setMetadata() method.

For example, to add metadata to an object in GCS:

const file = storage
        .bucket(bucketName)
        .file(filename)

const metadata = {
        metadata: {
                example: 'test'
        }
}

file.setMetadata(metadata)

// Get the updated Metadata
const get_metadata =  file.getMetadata();

// Will print `File: test`
console.log(`File: ${metadata.metadata.example}`)

To update it, you can retrieve the current metadata with the getMetadata() method, modifying it, and updating it with the setMetadata() method .

For example:

const storage = new Storage();

const file = storage
        .bucket(bucketName)
        .file(filename)

// Get the file's metadata 
const [metadata] = await file.getMetadata()

console.log(`File: ${metadata.name}`)

// update metadata    
file.setMetadata(metadata.metadata.example='updated')


// Get the updated metadata
const [get_metadata] = await file.getMetadata()
console.log(`File: ${get_metadata.metadata.example}`)
like image 155
Joan Grau Noël Avatar answered Oct 20 '25 20:10

Joan Grau Noël



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!