I would like to display the list of my google bucket storage files on my node.js app and I would like to know if it's possible or if I have to go by another way ? Thanks
Here is an example I wrote in Node.js 10 for GAE standard, which you can use and adapt:
app.js
'use strict';
const express = require('express');
const {Storage} = require('@google-cloud/storage');
const app = express();
app.get('/', async(req, res) => {
let bucketName = '<BUCKET-NAME>'
// Initiate a Storage client
const storage = new Storage();
// List files in the bucket and store their name in the array called 'result'
const [files] = await storage.bucket(bucketName).getFiles();
let result = [];
files.forEach(file => {
result.push(file.name);
});
// Send the result upon a successful request
res.status(200).send(result).end();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
package.json
{
"name": "nodejs-app",
"engines": {
"node": ">=8.0.0"
},
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "^4.16.3",
"@google-cloud/storage": "^4.1.3"
}
}
app.yaml
runtime: nodejs10
In order to get a list with the URLs instead of the file names change the following piece in the app.js sample provided above:
const [files] = await storage.bucket(bucketName).getFiles();
let result = [];
files.forEach(file => {
result.push("https://storage.cloud.google.com/" + bucketName + "/" + file.name);
});
Here is the code you can use instead in order to get the objects' metadata:
const [files] = await storage.bucket(bucketName).getFiles();
let result = [];
for (const file of files) {
const [metadata] = await file.getMetadata();
result.push(metadata.size);
};
res.status(200).send(result).end();