有没有一种方法可以通过 node.js 直接读取存储桶 Google Cloud Datastore 中 JSON 文件的内容,而无需事先下载?

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?

我是一名 Python 开发人员,但我现在正在从事的项目的情况迫使我在 Node.js.

中找到解决方案

我检查了 documentation 在 class 文件中,我有这个方法:createReadStream,但谁强迫我在读取之前先下载到本地。

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.

这是 createReadStream() 方法的脚本:

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

感谢您的理解与帮助。

是的,有可能,我为您做了以下代码,在云函数中完美运行:

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

这里有 package.json(依赖项):

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

脚本:

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