Writing your first CLI app
Last updated
Was this helpful?
Was this helpful?
dart compile exe hello.dart
Generated: hello.exe
./hello.exe
> Hello World
ll hello.exe
-rwxrwxr-x 1 5,875,400 Sep 5 14:30 hello.exe*name: hello_world
description: My first app that does bugger all.
dependencies:
dcli: ^7.0.0 # update the version no. to the latest; https://pub.dev/packages/dclidart pub get
Resolving dependencies...
Got dependencies!import 'package:dcli/dcli.dart';
void main() {
print("Now let's do someting useful.");
var username = ask( 'username:');
print('username: $username');
var password = ask( 'password:', hidden: true);
print('password: $password');
// create a directory
if (!exists('tmp')) {
createDir('tmp');
}
// Truncate any existing content
// of the file 'tmp/text.txt' and write
// 'Hello world' to the file.
'tmp/text.txt'.write('Hello world');
// append 'My second line' to the file 'tmp/text.txt'.
'tmp/text.txt'.append('My second line');
// and another append to the same file.
'tmp/text.txt'.append('My third line');
// now copy the file tmp/text.txt to second.txt
copy('tmp/text.txt', 'tmp/second.txt', overwrite: true);
// lets dump the file we just created to the console
read('tmp/second.txt').forEach((line) => print(line));
//let's prove that both files exist by running
// a recursive find.
find('*.txt').forEach((file) => print('Found $file'));
// Now let's tail the file using the OS tail command.
// DCli uses Dart extensions on the String class allowing us to
// treat a string
// as an OS command and `.run` that command as
// a child process.
// Stdout and stderr output are written
// directly to the console.
'tail tmp/text.txt'.run;
//Let's do a word count capturing stdout,
// stderr will will be swallowed.
'wc tmp/second.txt'.forEach((line) => print('Captured $line'));
if (confirm( "Should I delete 'tmp'? (y/n):")) {
// Now let's clean up
delete('tmp/text.txt');
delete('tmp/second.txt');
deleteDir('tmp');
}
}dart hello.dart
Now let's do someting useful.
username: auser
username: auser
password: *********
password: apassword
Hello world
My second line
My third line
Found /tmp/fred/tmp/second.txt
Found /tmp/fred/tmp/text.txt
Hello world
My second line
My third line
Captured 3 8 41 tmp/second.txt
Should I delete 'tmp'? (y/n): (y/n): y