首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NodeJS:用"through2“代替2021年的蒸汽干预

NodeJS:用"through2“代替2021年的蒸汽干预
EN

Stack Overflow用户
提问于 2021-02-02 09:45:47
回答 1查看 448关注 0票数 3

来自through2文档:

你需要这个吗? 自从Node.js引入简化流构造以来,through2的许多应用都变得冗余。考虑一下您是否真的需要使用through2,还是只想使用“可读-流”包,还是使用核心“流”包(从“可读-流”派生而来)。

如果我理解正确的话,现在(从2021年起)我们可以在没有第三方库的情况下对流进行干预。我没有找到如何做与through2流文档中相同的事情。

代码语言:javascript
复制
// ...
  .pipe(through2(function (file, encoding, callback) {
    // Do something with file ...
    callback(null, file)
   }))

// ↑ Possible to reach the same effect natively (with core packages)?

我想,对于2021年,必须有一些支持异步/等待语法的方法:

代码语言:javascript
复制
// ...
  .pipe(newFeatureOfModernNodeJS(async function (file) {

    await doSomethingAsyncWithFile(file);
    // on fail - same effect as "callback(new Error('...'))" of trough2

    return file; // same effect as "callback(null, file)" of trough2

    // or
    return null; // same effect as `callback()` of trough2
   }))

// ↑ Possible to reach the same effect natively (with core packages)?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-10 17:52:31

您要寻找的可能是转换流,这是由Node.js中包含的本机“流”库实现的。我还不知道是否有一个异步兼容的版本,但肯定有一个基于回调的版本。您需要从本机转换流继承并实现您的函数。

这是我喜欢使用的样板:

代码语言:javascript
复制
const Transform = require('stream').Transform;
const util      = require('util');

function TransformStream(transformFunction) {
  // Set the objectMode flag here if you're planning to iterate through a set of objects rather than bytes
  Transform.call(this, { objectMode: true });
  this.transformFunction = transformFunction;
}

util.inherits(TransformStream, Transform);

TransformStream.prototype._transform = function(obj, enc, done) {
  return this.transformFunction(this, obj, done);
};

module.exports = TransformStream;

现在,您可以在您可以通过以下方式使用的地方使用它:

代码语言:javascript
复制
const TransformStream = require('path/to/myTransformStream.js');
//...
.pipe(new TransformStream((function (file, encoding, callback) {
    // Do something with file ...
    callback(null, file)
 }))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66007171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档