Search code examples
dartstreampipestdin

How start process and read paramters from stdin input in dart?


I want to implement follow code in dart and start V2ray

cat ~/.config/qv2ray/vcore/config.json | v2ray

This is Node.js implement:

const result = child_process.spawn("v2ray", [], { input: str });

I spent a whole day solving this problem, but still couldn’t solve it


Solution

  • Made an example on how you can do it:

    import 'dart:convert';
    import 'dart:io';
    
    Future<void> main() async {
      final homeDir = getHomeDir();
    
      if (homeDir == null) {
        throw Exception('Could not find home directory on running platform!');
      }
    
      final process = await Process.start('v2ray', const []);
      final resultStdoutFuture = process.stdout
          .transform(const Utf8Decoder())
          .transform(const LineSplitter())
          .toList();
    
      await process.stdin
          .addStream(File('$homeDir/.config/qv2ray/vcore/config.json').openRead());
      await process.stdin.close();
    
      print('Process stopped with exit code: ${await process.exitCode}');
      print('Returned stdout:');
      (await resultStdoutFuture).forEach((logLine) => print('\t$logLine'));
    }
    
    String? getHomeDir() {
      final envVars = Platform.environment;
    
      if (Platform.isMacOS) {
        return envVars['HOME'];
      } else if (Platform.isLinux) {
        return envVars['HOME'];
      } else if (Platform.isWindows) {
        return envVars['UserProfile'];
      }
    }