代码之家  ›  专栏  ›  技术社区  ›  Aravindh

如何使用node js读取上传到google云存储的JSON文件内容

  •  2
  • Aravindh  · 技术社区  · 6 年前

    我用来读取元数据的代码是:

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

    1 回复  |  直到 4 年前
        1
  •  12
  •   F10    5 年前

    我使用以下代码从云存储中读取了一个json文件:

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

    我正在从一个流中读取并将文件中的所有数据concat到buf变量。

    希望有帮助。

    更新

    要读取多个文件:

    '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");
                });    
            });
    };
    
        2
  •  4
  •   Pratap Singh    5 年前

    有一种方便的方法:“下载”将文件下载到内存或本地目标。您可以使用以下下载方法:

    const bucketName='bucket name here';
    const fileName='file name here';
    const storage = new Storage.Storage();
    const file = storage.bucket(bucketName).file(fileName);
    
    file.download(function(err, contents) {
         console.log("file err: "+err);  
         console.log("file data: "+contents);   
    });