GCP Cloud Storage:bucket.upload 和 file.save 方法有什么区别?

GCP Cloud Storage: What is the difference between bucket.upload and file.save methods?

上传文件有更好的选择吗?

在我的情况下,我需要上传很多小文件(pdf 或文本),我必须决定最佳选择,但这两种方法之间有区别吗?

这里有两个直接取自文档的例子

保存方法: (Docs)

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

const file = myBucket.file('my-file');
const contents = 'This is the contents of the file.';

file.save(contents, function(err) {
  if (!err) {
    // File written successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.save(contents).then(function() {});

上传方式: (Docs)

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

//-
// Upload a file from a local path.
//-
bucket.upload('/local/path/image.png', function(err, file, apiResponse) {
  // Your bucket now contains:
  // - "image.png" (with the contents of `/local/path/image.png')

  // `file` is an instance of a File object that refers to your new file.
});

从本质上讲,这两个函数做同样的事情。他们将文件上传到存储桶。一个只是 bucket 上的函数,另一个是 file 上的函数。它们最终都调用了 file.createWriteStream,因此它们的性能也相同。

这些函数在上传类型方面表现不同。 file.save 将默认为可恢复上传,除非您另有指定(您可以将 SaveOptions 上的 resumable 布尔值设置为 false)。 bucket.upload 如果文件小于 5MB 将执行分段上传,否则将执行可续传上传。对于 bucket.upload,您可以通过修改 UploadOptions 上的 resumable 布尔值来强制进行可恢复或分段上传。

请注意,在即将发布的主要版本 (https://github.com/googleapis/nodejs-storage/pull/1876) 中,此行为将统一。无论文件大小如何,这两个功能都将默认为可恢复上传。行为将相同。

对于小文件,建议分段上传。