首页 > 解决方案 > 列出 node.js 应用中的 gcloud 存储桶文件

问题描述

我想在我的 node.js 应用程序上显示我的谷歌存储桶存储文件列表,我想知道这是否可能,或者我是否必须通过其他方式?谢谢

标签: node.jsgcloudbucket

解决方案


这是我在 Node.js 10 中为 GAE 标准编写的示例,您可以使用和调整它:

应用程序.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;

包.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"
  }
}

应用程序.yaml

runtime: nodejs10

为了获得包含URL而不是文件名的列表,请更改上面提供的app.js示例中的以下部分:

const [files] = await storage.bucket(bucketName).getFiles();
  let result = [];
  files.forEach(file => {
    result.push("https://storage.cloud.google.com/" + bucketName + "/" + file.name);
  });

编辑:获取对象的元数据

您可以使用以下代码来获取对象的元数据:

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();

Node.js 客户端库参考


推荐阅读