【问题标题】: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?有没有办法通过 node.js 直接读取存储桶 Google Cloud Datastore 中的 JSON 文件的内容,而无需事先下载?
【发布时间】:2023-03-17 05:11:01
【问题描述】:

我是一名 Python 开发人员,但我现在正在从事的项目的情况,迫使我在 Node.js 中找到解决方案。

我已经检查了documentation 在类文件中,我有这个方法:createReadStream,但是谁强迫我在阅读之前在本地下载。

但是,我搜索的解决方案就像将内容保存在一个变量中,以便我可以根据需要阅读和解释。

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

感谢您的理解和帮助。

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-storage google-api-nodejs-client


    【解决方案1】:

    是的,有可能,我为您编写了以下代码,在云功能中完美运行:

    /**
     * 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"
      }
    }

    【讨论】:

    • 感谢您的帮助,但我没有使用云功能解决此问题。
    【解决方案2】:

    脚本:

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

    【讨论】:

    • 我了解到您已经能够解决您的问题,您能否将您的答案标记为“已接受”以使 Stack Overflow 社区受益?提前谢谢你。
    猜你喜欢
    • 2017-08-05
    • 2021-01-17
    • 2020-01-18
    • 1970-01-01
    • 2016-12-12
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多