node.js - 列出 node.js 应用中的 gcloud 存储桶文件
问题描述
我想在我的 node.js 应用程序上显示我的谷歌存储桶存储文件列表,我想知道这是否可能,或者我是否必须通过其他方式?谢谢
解决方案
这是我在 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();
推荐阅读
- django - 用于创建具有不同权限的用户的 Django 表单
- postgresql - 在 PostgreSQL 中通过另一个表的值选择一列
- validation - ASP.NET Core 2.0 中的字段验证
- katalon-studio - 从 Katalon Recorder 导出页面文本
- ffmpeg - 无法将 mp4 上传到 youtube
- javascript - 使用 c# 使用凭据登录 HttpRequest(得到工作的 javascript 代码)
- python - 在 Python 中调试期间绘制函数
- r - 有没有可能的方法从纬度/经度或地址到 R 中的县细分名称和 FIPS 代码?
- aframe - 带有徽标的网址的 A 帧链接
- javascript - 在 D3 的上下文菜单中获取节点详细信息