[英]Download via http and streaming upload to Google Cloud storage using nodejs
I am fighting to get a download to directly stream to GCS without saving to the file system, see below snippet. 我正在争取获得一个直接下载到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`);
});
};
On finish is never triggered. 完成时永远不会触发。 No output whatsoever.
没有任何输出。 I can stream http.get to a local file without problems, so that part seems to be OK.
我可以将http.get流式传输到本地文件而不会出现问题,因此该部分似乎还可以。
What also works is streaming from the local filesystem to GCS, like below : 也可以从本地文件系统流到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`);
});
};
The second snippet logs 'success' and the file is present on the bucket. 第二个片段记录为“成功”,并且文件存在于存储桶中。
Both http.get
and fs.createReadStream
create a read stream. http.get
和fs.createReadStream
创建读取流。
What am I doing wrong here ? 我在这里做错了什么?
Switching over to the request
library does work : 切换到
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`);
});
};
Still unsure why http
library does not. 仍然不确定为什么
http
库没有。
the request library works with promises whereas the http lib needs a callback : 请求库可以使用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.