From b251c5f2e20ef1b635c925c749292148251dac29 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Mon, 18 Nov 2019 00:05:02 +0800 Subject: [PATCH] add read from stdin --- prettyjson.dart | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/prettyjson.dart b/prettyjson.dart index b063714..b026bf2 100644 --- a/prettyjson.dart +++ b/prettyjson.dart @@ -1,13 +1,26 @@ import 'dart:convert'; import 'dart:io'; -main(List args) async { - if (args.length == 0) { - print('File name is not assigned\nUsage: prettyjson.dart '); - return; - } - final jsonContent = await new File(args[0]).readAsString(); +main(List args) async { + final jsonContent = await readContent(args); final jsonDecoded = json.decode(jsonContent); JsonEncoder encoder = new JsonEncoder.withIndent(' '); print(encoder.convert(jsonDecoded)); } + +Future readContent(List args) async { + if (args.length == 0) { + return readFromStdin(); + } else { + return new File(args[0]).readAsString(); + } +} + +Future readFromStdin() async { + final stdinContentLines = stdin.transform(utf8.decoder); + final stdinContentArray = new List(); + await for (var line in stdinContentLines) { + stdinContentArray.add(line); + } + return Future.value(stdinContentArray.join('\n')); +}