如何使用Node JS读取上传到Google云存储的JSON文件的内容
问题描述:
我通过创建一个新项目将JSON文件手动上传到Google云存储.我能够读取文件的元数据,但是我不知道如何读取JSON内容.
I manually upload the JSON file to google cloud storage by creating a new project. I am able to read the metadata for a file but I don't know how to read the JSON content.
我用来读取元数据的代码是:
The code I used to read the metadata is:
var Storage = require('@google-cloud/storage');
const storage = Storage({
keyFilename: 'service-account-file-path',
projectId: 'project-id'
});
storage
.bucket('project-name')
.file('file-name')
.getMetadata()
.then(results => {
console.log("results is", results[0])
})
.catch(err => {
console.error('ERROR:', err);
});
有人可以指导我阅读JSON文件内容的方法吗?
Can someone guide me to the way to read the JSON file content?
答
我使用以下代码从Cloud Storage中读取json文件:
I've used the following code to read a json file from Cloud Storage:
'use strict';
const Storage = require('@google-cloud/storage');
const storage = Storage();
exports.readFile = (req, res) => {
console.log('Reading File');
var archivo = storage.bucket('your-bucket').file('your-JSON-file').createReadStream();
console.log('Concat Data');
var buf = '';
archivo.on('data', function(d) {
buf += d;
}).on('end', function() {
console.log(buf);
console.log("End");
res.send(buf);
});
};
我正在从流中读取并将文件中的所有数据合并到buf变量.
I'm reading from a stream and concat all the data within the file to the buf variable.
希望有帮助.
更新
要读取多个文件,请执行以下操作:
To read multiple files:
'use strict';
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
listFiles();
async function listFiles() {
const bucketName = 'your-bucket'
console.log('Listing objects in a Bucket');
const [files] = await storage.bucket(bucketName).getFiles();
files.forEach(file => {
console.log('Reading: '+file.name);
var archivo = file.createReadStream();
console.log('Concat Data');
var buf = '';
archivo.on('data', function(d) {
buf += d;
}).on('end', function() {
console.log(buf);
console.log("End");
});
});
};