【问题标题】:wrapping nodejs stream in JSON object在 JSON 对象中包装 nodejs 流
【发布时间】:2018-03-21 02:15:38
【问题描述】:

我有一个可读的流,像这样:

const algorithm = 'aes-256-ctr';
stream = file.stream
    .pipe(crypto.createCipher(algorithm, encryptionKey))
    .pipe(outStream);

加密在整个文件上按预期工作。 我需要将加密的结果包装成某种 json,所以输出流接收这样的东西:

{
    "content": "/* MY STREAM CONTENT */"
}

我该怎么做?

此外,如果加密密钥匹配,我需要读取存储在磁盘上的文件并将其从 json 中解包。

提前致谢

【问题讨论】:

  • Writing node.js stream into a string variable 的可能重复项。我认为该线程会告诉您您需要知道的一切。
  • 不是真的,我包装后的结果需要是一个流,而不是存储在变量中的值。但感谢您的关注。
  • 并且我期望在包装后在最后写入下一个流的转换流中的更多内容,这是使用流的正确方法吗?假设所有内容都保留在内存中直到读取结束?
  • 是的。这就是你需要做的。这只是网络上许多示例的变体。大多数变换对象。你想建造一个。
  • 是的,你能找到一些我可以使用的起点吗?

标签: json node.js stream transform-stream


【解决方案1】:

从节点 v13 开始,您可以在 pipeline 中使用 generators 并将您的对象构建为字符串:

// const { pipeline } = require('stream/promises'); // <- node >= 16
const Util = require('util');
const pipeline = Util.promisify(Stream.pipeline);

const algorithm = 'aes-256-ctr';
const Crypto = require('crypto');

async function run() {
  await pipeline(
    file.stream, // <- your file read stream
    Crypto.createCipher(algorithm, encryptionKey),
    chunksToJson,
    outStream
  );
}

async function* chunksToJson(chunksAsync) {
  yield '{"content": "';
  for await (const chunk of chunksAsync) {
    yield Buffer.isBuffer(chunk) ? chunk.toString('utf8') : JSON.stringify(chunk);
  }
  yield '"}';
}

假设正在流式传输大量数据的更复杂情况(使用流时通常是这种情况),您可能会尝试执行以下操作。这不是一个好的做法,因为所有content 都会在屈服之前在内存中累积,从而违背了流式传输的目的。

async function* chunksToJson(chunksAsync) {
  const json = { content: [] };
  for await (const chunk of chunksAsync) {
    json.content.push(Buffer.isBuffer(chunk) ? chunk.toString('utf8') : JSON.stringify(chunk));
  }
  yield JSON.stringify(json);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-15
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多