如何使用节点 js 读取上传到谷歌云存储的 JSON 文件的内容 [英] How to read content of JSON file uploaded to google cloud storage using node js

查看:30
本文介绍了如何使用节点 js 读取上传到谷歌云存储的 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);
    });

Can someone guide me to the way to read the JSON file content?

解决方案

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

    };

I'm reading from a stream and concat all the data within the file to the buf variable.

Hope it helps.

UPDATE

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");
            });    
        });
};

这篇关于如何使用节点 js 读取上传到谷歌云存储的 JSON 文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆