【问题标题】:Upload text file to Google Cloud storage with ASCII encoding with node使用节点的 ASCII 编码将文本文件上传到 Google Cloud 存储
【发布时间】:2021-09-07 22:09:41
【问题描述】:

与我合作的旧版第 3 方要求我们为他们提供使用 ANSI (~ASCII) 字符编码的文本文件。

要保存到文件的内容很大,所以我使用流。如果使用 fs 库,我可以这样做:

const file = fs.createWriteStream(filePath, {encoding: 'ascii'});

data.pipe(file).on('error', handleError).on('finish', handleSuccess);

我正在尝试在 GCS 节点客户端中进行等效操作:

const storage = new Storage();
const gcsFile = storage.bucket(bucket).file(fileName, {});

const fileStream = gcsFile.createWriteStream();


data.pipe(fileStream).on('error', handleError).on('finish', handleSuccess);

但是createWriteStream 方法没有这样的选项来指定字符编码。

有没有办法使用 ASCII 字符编码将数据显式流式传输到 GCS?

【问题讨论】:

  • 您是否收到任何错误或任何无法正常工作的特定内容?
  • 我的问题是关于使用 ASCII 编码将文件保存到 GCS 的可能性。 GCS 客户端库没有提供像fs 那样指定编码的选项
  • 您可能必须使用REST API 来使用流上传,否则如果您仅在没有流的情况下上传,NodeSDK 可以完美运行。

标签: node.js character-encoding google-cloud-storage


【解决方案1】:

我认为您可以将options.metadata 传递给createWriteStream。以下内容对您有用吗?

gcsFile = gcsBucket.file(fileName);

fs.createReadStream('myLocalFile.txt')
    .pipe(myFile.createWriteStream({
        metadata: {
            contentEncoding: 'ascii'
        }
    }))
    .on('error', handleError)
    .on('finish', handleSuccess);

在此处查看客户端参考文档:https://googleapis.dev/nodejs/storage/latest/global.html#CreateWriteStreamOptions

【讨论】:

  • 我看到了,但假设内容编码与字符集/字符编码不同。 TBH 我不太了解其中的复杂性。通过一些测试,我发现除非您使用非 ascii 字符,否则文件似乎默认使用 us-ascii 字符集。只有当我添加像“?”这样的字符时,字符集才会变成 utf-8。所以我认为元数据是多余的
  • 你是对的!您需要设置的元数据是 contentType,不是 contentEncoding。您可以尝试设置contentType: 'text/plain' 吗?或者你需要的任何类型,真的。
猜你喜欢
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2018-10-31
相关资源
最近更新 更多