【问题标题】:NodeJS: Actual native substitute for "through2" for intervention to steams in 2021NodeJS:“through2”的实际原生替代品,用于在 2021 年干预 Steam
【发布时间】:2021-02-11 03:08:03
【问题描述】:

来自through2 文档:

你需要这个吗?

自从 Node.js 引入了 Simplified Stream Construction,许多使用 through2 变得多余了。考虑你是否真的需要 使用 through2 或只想使用“可读流”包,或者 核心“流”包(派生自“可读流”)。

如果我理解正确,现在(从 2021 年开始)我们可以在没有第三方库的情况下干预流。 我在Stream documentation 中没有找到与through2 相同的操作。

// ...
  .pipe(through2(function (file, encoding, callback) {
    // Do something with file ...
    callback(null, file)
   }))

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

我想,2021 年肯定有一些方法支持 async/await 语法:

// ...
  .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)?

【问题讨论】:

    标签: node.js through2


    【解决方案1】:

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

    这是我喜欢使用的样板:

    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;
    

    现在你可以在你会使用的地方使用它:

    const TransformStream = require('path/to/myTransformStream.js');
    //...
    .pipe(new TransformStream((function (file, encoding, callback) {
        // Do something with file ...
        callback(null, file)
     }))
    

    【讨论】:

    • 老哥,这个问题和2021有关,请问用es6写代码好吗?!!! :)
    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多