gpt4 book ai didi

node.js - Node : How can I use pipe and change one file from a multipart

转载 作者:搜寻专家 更新时间:2023-10-31 23:20:28 25 4
gpt4 key购买 nike

我有一个需要重定向请求的 http 服务,我没有使用流,因为我处理多部分的大文件并且它会占用 RAM 或磁盘(参见 How do Node.js Streams work?)

现在我正在使用管道并且它可以工作,代码是这样的:

var Req = getReq(response);
request.pipe(Req);

唯一的缺点是,在这个多部分中,我在管道中重新发送包含一个需要更改几个字段的 JSON 文件。

我仍然可以使用管道并更改管道多部分中的一个文件吗?

最佳答案

您可以使用 Transform Stream 来做到这一点.

var Req = getReq(response);
var transformStream = new TransformStream();

// the boundary key for the multipart is in the headers['content-type']
// if this isn't set, the multipart request would be invalid
Req.headers['content-type'] = request.headers['content-type'];

// pipe from request to our transform stream, and then to Req
// it will pipe chunks, so it won't use too much RAM
// however, you will have to keep the JSON you want to modify in memory
request.pipe(transformStream).pipe(Req);

转换流代码:

var Transform = require('stream').Transform,
util = require('util');

var TransformStream = function() {
Transform.call(this, {objectMode: true});
};
util.inherits(TransformStream, Transform);

TransformStream.prototype._transform = function(chunk, encoding, callback) {

// here should be the "modify" logic;

// this will push all chunks as they come, leaving the multipart unchanged
// there's no limitation on what you can push
// you can push nothing, or you can push an entire file
this.push(chunk);
callback();
};

TransformStream.prototype._flush = function (callback) {
// you can push in _flush
// this.push( SOMETHING );
callback();
};

在 _transform 函数中,你的逻辑应该是这样的:

  1. 如果,在当前 block 中,您要修改的 JSON 开始

    <SOME_DATA_BEFORE_JSON> <MY_JSON_START>

    然后 this.push(SOME_DATA_BEFORE_JSON);并保持 MY_JSON_START在本地变量中

  2. 当您的 JSON 尚未结束时,将 block 附加到您的本地变量

  3. 如果在当前 block 中,JSON 结束:

    <JSON_END> <SOME_DATA_AFTER_JSON>

    然后添加JSON_END对你的 var,做你想做的任何改变,并推送更改: this.push(local_var); this.push(SOME_DATA_AFTER_JSON);

  4. 如果当前 block 没有您的 JSON,只需推送该 block

    this.push(chunk);

除此之外,您可能还想阅读 multipart format . SOME_DATA_BEFORE_JSON从上面将是:

--frontier
Content-Type: text/plain

<JSON_START>

除了Content-Type,还可能包含文件名、编码等。需要记住的是, block 可能会在任何地方结束(可能会在边界的中间结束)。解析可能会变得非常棘手;我会搜索边界键(frontier),然后检查 JSON 是否在此之后开始。有两种情况:

  1. block :<SOME_DATA> --frontier <FILE METADATA> <FILE_DATA>
  2. block 1:<SOME_DATA> --fron block 2:ier <FILE METADATA> <FILE_DATA>

希望这对您有所帮助!

关于node.js - Node : How can I use pipe and change one file from a multipart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38854913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com