Nodejs 可读流与 array.map

问题描述 投票:0回答:1

在学习流时,提供了以下示例:

  const data = ['some', 'data', 'to', 'read']
  const { Readable } = require('stream')
  const readable = Readable.from(data)
  readable.on('data', (data) => { console.log('got data:', data) })
  readable.on('end', () => { console.log('finished reading') })

这当然会输出

got data: some
,然后是
got data: data
,对于每个数组元素,依此类推。

我理解为什么教程会使用一个简单的例子;然而,我很难想象这个片段的现实世界用例。

说到该语句的基本实用性,它似乎只不过是对任何其他循环数组的方式的混淆:

  // eg.
  const data = ['some', 'data', 'to', 'read']
  data.map(data => console.log('got data:', data));

我认为第二个的好处是简洁,而第一个的缺点是复杂。但是,第二个片段缺乏绑定流事件的灵活性。还有哪些其他信息有助于理解何时以及在什么情况下以这种方式实现读取流?

请分享一个使用可读流(来自数组或其他方式)的代码片段,以展示灵活性的力量。还可以分享任何注释,以更好地解释为什么可读流在这种情况或其他情况下更有用。

node.js theory nodejs-stream
1个回答
0
投票

#更多示例

 const { Readable, Transform, pipeline } = require('stream');
    
    // Create an array of objects
    const data = [
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 28 },
    ];
    
    // Create a Readable stream from the array
    const readable = Readable.from(data);
    
    // Create a Transform stream to modify the data
    const transformStream = new Transform({
      objectMode: true,
      transform(chunk, encoding, callback) {
        chunk.age++; // Increment age for each object
        callback(null, chunk);
      },
    });
    
    // Pipe the readable stream through the transform stream and log the modified data
    pipeline(
      readable,
      transformStream,
      process.stdout, // Output to the console
      (err) => {
        if (err) {
          console.error('Pipeline failed.', err);
        } else {
          console.log('Pipeline succeeded.');
        }
      }
    );
© www.soinside.com 2019 - 2024. All rights reserved.