2021-10-26 编写dart command-line a

2021-10-26  本文已影响0人  我是小胡胡分胡

一、单个dart文件

1,创建简单dart文件,可以直接运行,不需要依赖

创建helloworld.dart
编写代码:

void main() {
  print('Hello, World!');
}

2,运行程序

 dart run helloworld.dart 

二、需要其他依赖的dart项目

1,创建dart项目

dart create dcat
image.png

2,添加依赖

 cd dcat/
dart pub add args

该命令在pubspec.yaml下面添加了依赖。

image.png

3,编写代码

dcat.dart

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

import 'package:args/args.dart';

const lineNumber = 'line-number';

void main(List<String> arguments) {
  exitCode = 0; // presume success
  final parser = ArgParser()..addFlag(lineNumber, negatable: false, abbr: 'n');

  ArgResults argResults = parser.parse(arguments);
  final paths = argResults.rest;

  dcat(paths, showLineNumbers: argResults[lineNumber] as bool);
}

Future<void> dcat(List<String> paths, {bool showLineNumbers = false}) async {
  if (paths.isEmpty) {
    // No files provided as arguments. Read from stdin and print each line.
    await stdin.pipe(stdout);
  } else {
    for (final path in paths) {
      var lineNumber = 1;
      final lines = utf8.decoder
          .bind(File(path).openRead())
          .transform(const LineSplitter());
      try {
        await for (final line in lines) {
          if (showLineNumbers) {
            stdout.write('${lineNumber++} ');
          }
          stdout.writeln(line);
        }
      } catch (_) {
        await _handleError(path);
      }
    }
  }
}

Future<void> _handleError(String path) async {
  if (await FileSystemEntity.isDirectory(path)) {
    stderr.writeln('error: $path is a directory');
  } else {
    exitCode = 2;
  }
}

4,运行程序

dart run bin/dcat.dart -n  README.md pubspec.yaml 

该程序的作用就是在终端打印命令行参数后面的每一个文件的内容

上一篇下一篇

猜你喜欢

热点阅读