繁体   English   中英

通过http下载并使用Node.js流传输到Google Cloud存储

[英]Download via http and streaming upload to Google Cloud storage using nodejs

我正在争取获得一个直接下载到GCS而不保存到文件系统的下载,请参见下面的代码片段。

const { Storage } = require('@google-cloud/storage');
const http = require('http');
const storage = new Storage();
const fs = require("fs");
const bucketName = 'BUCKETNAMEHERE';
const blobName = 'image.jpg';
const bucket = storage.bucket(bucketName);
const blob = bucket.file(blobName);

const streamDownload = () => {
    http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg")
        .pipe(blob.createWriteStream({
            metadata: {
                contentType: 'image/jpg'
            }
        }))
        .on("error", (err) => {
            console.error(`error occurred`);
        })
        .on('finish', () => {
            console.info(`success`);
        });
};

完成时永远不会触发。 没有任何输出。 我可以将http.get流式传输到本地文件而不会出现问题,因此该部分似乎还可以。

也可以从本地文件系统流到GCS,如下所示:

const streamFs = () => {
    fs.createReadStream('/path/to/mqdefault.jpg')
        .pipe(blob.createWriteStream({
            metadata: {
                contentType: 'image/jpg'
            }
        }))
        .on("error", (err) => {
            console.error(`error occurred`);
        })
        .on('finish', () => {
            console.info(`success`);
        });
};

第二个片段记录为“成功”,并且文件存在于存储桶中。

http.getfs.createReadStream创建读取流。

我在这里做错了什么?

切换到request库确实可以:

const request = require('request');
const streamDownload = () => {
    request.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg")
        .pipe(blob.createWriteStream({
            metadata: {
                contentType: 'image/jpg'
            }
        }))
        .on("error", (err) => {
            console.error(`error occurred`);
        })
        .on('finish', () => {
            console.info(`success`);
        });
};

仍然不确定为什么http库没有。

请求库可以使用promise,而http lib需要回调:

const streamDownload = () => {

  var stream = blob.createWriteStream({
    metadata: {
        contentType: 'image/jpg'
    }
  })

  http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(res){
        stream.on("error", (err) => {
            console.error(`error occurred`);
        })
        stream.on('finish', () => {
            console.info(`success`);
        });
        res.pipe(stream)            
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM