Is there a way to directly read the content of a JSON file in a bucket Google Cloud Datastore via node.js without having to download it before?

柔情痞子 提交于 2021-01-29 14:23:44

问题


I am a Python developer, but the circumstances of a project I am working on now, oblige me to find a solution in Node.js.

I have check the documentation In the class File, I have this method: createReadStream, but who force me to download in local before read it.

However, the solution I search is just like to save the content in a variable so that I can read and interpret as I want.

This is the script of createReadStream() method:

var storage = require('@google-cloud/storage')();
var bucket = storage.bucket('my-bucket');

var fs = require('fs');
var remoteFile = bucket.file('image.png');
var localFilename = '/Users/stephen/Photos/image.png';

remoteFile.createReadStream()
  .on('error', function(err) {})
  .on('response', function(response) {
    // Server connected and responded with the specified status
   })
  .on('end', function() {
    // The file is fully downloaded.
  })
  .pipe(fs.createWriteStream(localFilename));

Thank's for your understanding and help.


回答1:


Script:

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket(bucket);
const remoteFile = bucket.file(file);

let buffer = '';
remoteFile.createReadStream()
  .on('error', function(err) {console.log(err)})
  .on('data', function(response) {
    buffer += response
  })
  .on('end', function() {
    //console.log(buffer);
    res.send(buffer);
  })



回答2:


Yes, it is possible, I did the following code for you, works perfectly in a cloud function:

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */

'use strict';

const gcs = require('@google-cloud/storage')();

exports.readJSON = (req, res) => {
  let file = gcs.bucket('YOUR_BUCKET').file('YOUR_FILE.JSON');
  let readStream = file.createReadStream();
  res.send(readStream);
};

and here you have the package.json (dependencies):

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
  	"@google-cloud/storage": "1.6.0"
  }
}


来源:https://stackoverflow.com/questions/53392131/is-there-a-way-to-directly-read-the-content-of-a-json-file-in-a-bucket-google-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!