Dart: How to pass data from one process to another via streams

自闭症网瘾萝莉.ら 提交于 2021-02-11 08:45:49

问题


I need the ability to start two processes from dart, read the input from the first process, manipulate the output in dart and then send the data to a second process.

Note: in this example I state two processes but in reality I may need to create a pipe line involving any number of processes.

The two process are likely to be long running (assume minutes) and the output must be available as the processes process the data (think tail -f).

To re-inforce the last point the process may output large amounts of data so the data can't be stored in memory hence the stream approach that I've attempted.

I've tried the following but I'm not experienced with streams so I'm not even certain if I'm on the right track.

https://dartpad.dev/3ad46c7e28c80f6735a9ee350091d509


回答1:


You can use Stream.pipe:

import 'dart:convert';
import 'dart:io';

void main() async {
  var ls = await Process.start('ls', []);
  var head = await Process.start('head', ['-1']);

  ls.stdout
      .transform(utf8.decoder)
      .transform(const LineSplitter())
      .map((line) => '1: $line\n')
      .transform(utf8.encoder)
      .pipe(head.stdin)
      .catchError(
        (e) {
          // forget broken pipe after head process exit
        },
        test: (e) => e is SocketException && e.osError.message == 'Broken pipe',
      );

  await head.stdout.pipe(stdout);
}


来源:https://stackoverflow.com/questions/59746768/dart-how-to-pass-data-from-one-process-to-another-via-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!