OLD | NEW |
---|---|
(Empty) | |
1 --- | |
2 layout: default | |
3 title: "Write Command-Line Apps" | |
4 description: "Basics for command-line apps" | |
5 has-permalinks: true | |
6 tutorial: | |
7 id: dart-io | |
8 next: / | |
9 next-title: "Home" | |
10 prev: indexeddb/ | |
11 prev-title: "Use IndexedDB" | |
12 --- | |
13 | |
14 {% capture whats_the_point %} | |
15 | |
16 * Command-line applications need to do input and output. | |
17 * The dart:io library provides I/O functionality. | |
18 * The args package helps define and parse command-line arguments. | |
19 * Most input and output requires the use of Streams. | |
20 * Streams provide a series of asynchronous data events. | |
21 * To handle asynchronous data, you need to use Futures. | |
22 | |
23 {% endcapture %} | |
24 | |
25 {% capture sample_links %} | |
26 | |
27 <p> This tutorial features these examples:</p> | |
28 * helloworld | |
29 * dcat | |
30 | |
31 <p> | |
32 Don't have the source code? | |
33 <a href="https://github.com/dart-lang/dart-tutorials-samples/archive/master.zip" > | |
34 Download it. | |
35 </a> | |
36 | |
37 {% endcapture %} | |
38 | |
39 {% capture content %} | |
40 | |
41 <div class="tute-target-title"> | |
42 <h1>{{page.title}}</h1> | |
43 <h3>An introduction to standalone apps</h3> | |
44 </div> | |
45 | |
46 This tutorial teaches you how to build command-line apps | |
47 and shows you a few small command-line applications. | |
48 These programs use resources that most command-line applications need, | |
49 including the standard output, error, and input streams, | |
50 command-line arguments, files and directories, and more. | |
51 | |
52 * [Running an app with the standalone Dart VM](#run-the-first-app) | |
53 * [Review briefly the dcat example code](#dcat-code) | |
54 * [Parsing command-line arguments](#cmd-line-args) | |
55 * [Reading and writing with stdin, stdout, and stderr](#std-in-out-err) | |
56 * [Getting info about a file](#filesystementity) | |
57 * [Reading a file](#reading-a-file) | |
58 * [Writing a file](#writing-a-file) | |
59 * [Getting environment information](#env-var) | |
60 * [Setting exit codes](#exit-codes) | |
61 * [Summary](#summary) | |
62 * [Other resources](#other-resources) | |
63 * [What next?](#what-next) | |
64 | |
65 ## Running an app with the standalone Dart VM {#run-the-first-app} | |
66 | |
67 To run a command-line app, you need the Dart VM (`dart`), | |
68 which comes in the [Dart SDK download](/tools/sdk/). | |
69 (If you downloaded Dart Editor, you already have the Dart VM.) | |
70 | |
71 If you installed the Dart download in a directory called `~/myDartDownload`, | |
72 you can find `dart` | |
73 in `~/myDartDownload/dart-sdk/bin`. | |
74 | |
75 <div markdown="1"> | |
76 | |
77  | |
78 | |
79 </div> | |
80 | |
81 By putting this directory in your PATH | |
82 you can refer to the `dart` command and other commands, | |
83 such as the dart analyzer, by name. | |
84 | |
85 Let's run a small program. | |
86 | |
87 <ol> | |
88 <li markdown="1"> | |
89 Create a file called `helloworld.dart` that contains this code: | |
90 | |
91 {% prettify dart %} | |
92 void main() { | |
93 print('Hello, World!'); | |
94 } | |
95 {% endprettify %} | |
96 </li> | |
97 | |
98 <li markdown="1"> | |
99 In the directory that contains the file you just created, | |
100 run the program with the command as shown by the highlighted text. | |
101 | |
102 {% prettify bash %} | |
103 % [[highlight]]dart helloworld.dart[[/highlight]] | |
104 Hello, World! | |
105 % | |
106 {% endprettify %} | |
107 | |
108 </li> | |
109 </ol> | |
110 | |
111 ### Running in checked mode | |
112 | |
113 You can run the Dart VM in checked mode by using the `--checked` flag. | |
sethladd
2014/01/03 17:54:54
Can we lead with why you might want to do this? Or
mem
2014/01/03 19:22:14
Done.
| |
114 | |
115 {% prettify bash %} | |
116 % [[highlight]]dart --checked helloworld.dart[[/highlight]] | |
117 Hello, World! | |
118 % | |
119 {% endprettify %} | |
120 | |
121 The `--checked` option enables assertion and type checks. | |
122 Checked mode is useful during development for finding errors | |
123 related to types and for testing `assert` statements. | |
124 We recommend running your programs in checked mode during prototyping | |
125 and development, and turning it off for production. | |
126 | |
127 Note that the flags and options passed to the Dart VM go before the name | |
128 of the Dart file to run. | |
129 | |
130 ## Review briefly the dcat example code {#dcat-code} | |
131 | |
132 Take a quick look at the code for a small sample called `dcat`, | |
133 which displays the contents of any files listed on the command line. | |
134 This program uses various classes, functions, and properties | |
135 available to command-line apps. | |
136 This tutorial goes into detail about this app in the following sections. | |
137 For a brief look now, hover over the highlighted code below for explanations. | |
138 | |
139 <pre class="prettyprint lang-dart"> | |
140 import 'dart:async'; | |
141 import 'dart:convert'; | |
142 import 'dart:io'; | |
143 | |
144 import 'package:args/args.dart'; | |
145 | |
146 const LINE_NUMBER = 'line-number'; | |
147 var NEWLINE = '\n'; | |
148 | |
149 ArgResults argResults; | |
150 | |
151 void main(<a href="#" class="dart-popover" data-toggle="popover" title="Command- line arguments" data-html="true" data-trigger="hover focus" data-content="Comman d-line arguments are passed in by the system when the program starts.">List<S tring> arguments</a>) { | |
152 final parser = new ArgParser() | |
153 ..addFlag(LINE_NUMBER, negatable: false, abbr: 'n'); | |
154 | |
155 <a href="#" class="dart-popover" data-toggle="popover" title="Arguments parser " data-html="true" data-trigger="hover focus" data-content="The ArgParser class provides help with parsing command-line arguments.">argResults = parser.parse(ar guments);</a> | |
156 List<String> paths = argResults.rest; | |
157 | |
158 dcat(paths, argResults[LINE_NUMBER]); | |
159 } | |
160 | |
161 Future dcat(List<String> paths, bool showLineNumbers) { | |
162 if (paths.isEmpty) { | |
163 // No files provided as arguments. Read from stdin and print each line. | |
164 return <a href="#" class="dart-popover" data-toggle="popover" title="Standar d I/O streams" data-html="true" data-trigger="hover focus" data-content="This co de reads from the standard input stream and pipes the data to the standard outpu t stream.">stdin.pipe(stdout);</a> | |
165 } else { | |
166 return Future.forEach(paths, (path) { | |
167 int lineNumber = 1; | |
168 <a href="#" class="dart-popover" data-toggle="popover" title="Open a file for reading" data-html="true" data-trigger="hover focus" data-content="Use the F ile class to represent a file on the native file system.">Stream<List<int& gt;> stream = new File(path).openRead();</a> | |
169 return stream | |
170 <a href="#" class="dart-popover" data-toggle="popover" title="Data con verters" data-html="true" data-trigger="hover focus" data-content="Convert data as it becomes available on a stream.">.transform(UTF8.decoder)</a> | |
171 .transform(const LineSplitter()) | |
172 <a href="#" class="dart-popover" data-toggle="popover" title="Get data from a stream" data-html="true" data-trigger="hover focus" data-content="Listen to a stream to get data when it becomes available.">.listen((line)</a> { | |
173 if (showLineNumbers) { | |
174 stdout.write('${lineNumber++} '); | |
175 } | |
176 stdout.writeln(line); | |
177 }).asFuture().catchError((_) => _handleError(path)); | |
178 }); | |
179 } | |
180 } | |
181 | |
182 _handleError(String path) { | |
183 <a href="#" class="dart-popover" data-toggle="popover" title="Test a path" dat a-html="true" data-trigger="hover focus" data-content="You can get information a bout the file system on which your program is running.">FileSystemEntity.isDirec tory(path)</a>.then((isDir) { | |
184 if (isDir) { | |
185 print('error: $path is a directory'); | |
186 } else { | |
187 print('error: $path not found'); | |
188 } | |
189 }); | |
190 <a href="#" class="dart-popover" data-toggle="popover" title="Exit code" data- html="true" data-trigger="hover focus" data-content="A well-behaved command-line app sets an exit code to indicate whether the program was successful.">exitCode = 2;</a> | |
191 } | |
192 | |
193 </pre> | |
194 | |
195 ## Parsing command-line arguments {#cmd-line-args} | |
196 | |
197 The | |
198 <a href="https://api.dartlang.org/args.html" target="_blank">args</a> | |
199 package, a software bundle that contains a library of Dart code, provides | |
200 parser support for transforming raw command-line arguments | |
201 into a set of options, flags, and additional values. | |
202 Import the library as follows: | |
203 | |
204 {% prettify dart %} | |
205 import 'package:args/args.dart'; | |
206 {% endprettify %} | |
207 | |
208 The args library contains two classes: | |
209 | |
210 | Library | Description | | |
211 |---|---| | |
212 | <a href="https://api.dartlang.org/args/ArgParser" target="_blank">ArgParser</a > | A class that parses command-line arguments | | |
213 | <a href="https://api.dartlang.org/args/ArgResults" target="_blank">ArgResults< /a> | The result of parsing command-line arguments using ArgParser. | | |
214 {: .table } | |
215 | |
216 Let's take a look at the `dcat` sample, | |
217 which uses ArgParser and ArgResults to parse and store its command-line argument s. | |
218 | |
219 <ol> | |
220 <li markdown="1"> | |
221 Copy the sample file from the github repo: | |
222 <a href="https://github.com/dart-lang/dart-tutorials-samples/blob/master/bin/dca t.dart">dcat.dart</a>. | |
223 </li> | |
224 | |
225 <li markdown="1"> | |
226 Run the program from the command line as shown by the highlighted text. | |
227 | |
228 {% prettify bash %} | |
229 $ [[highlight]]dart dcat.dart -n quotes.txt[[/highlight]] | |
230 1 Be yourself. Everyone else is taken. -Oscar Wilde | |
231 2 Don't cry because it's over, smile because it happened. -Dr. Seuss | |
232 3 You only live once, but if you do it right, once is enough. -Mae West | |
233 ... | |
234 {% endprettify %} | |
235 | |
236 The program displays the contents of the source code file and | |
237 preceeds each line with a line number. | |
238 </li> | |
239 | |
240 </ol> | |
241 | |
242 The following diagram shows how the `dcat` command line used above | |
243 is parsed into the `ArgResults` object. | |
244 | |
245  | |
246 | |
247 You can access flags and options by name, | |
248 treating the ArgResults object like a Map. | |
249 You can access other values with properties such as `rest`. | |
250 | |
251 Here's the code from `dcat` that deals with command-line arguments: | |
252 | |
253 <pre class="prettyprint lang-dart"> | |
254 | |
255 ... | |
256 <a href="#" class="dart-popover" data-toggle="popover" title="Parsed arguments" data-html="true" data-trigger="hover focus" data-content="This object contains p arsed options and flags.">ArgResults argResults;</a> | |
257 | |
258 void main(<a href="#" class="dart-popover" data-toggle="popover" title="Command- line arguments" data-html="true" data-trigger="hover focus" data-content="The sy stem passes command-line arguments into the program in a list of strings.">List& lt;String> arguments</a>) { | |
259 final parser = new ArgParser() | |
260 <a href="#" class="dart-popover" data-toggle="popover" title="Define a val id flag" data-html="true" data-trigger="hover focus" data-content="Add a flag de finition to the command-line argument parser. This code defines the flag -n, whi ch when used displays line numbers.">..addFlag(LINE_NUMBER, negatable: false, ab br: 'n')</a>; | |
261 | |
262 argResults = parser.<a href="#" class="dart-popover" data-toggle="popover" tit le="Parse the arguments" data-html="true" data-trigger="hover focus" data-conten t="Parse the arguments that were passed into the main() function. The parser sto ps parsing if it finds an undefined option or flag.">parse(arguments)</a>; | |
263 List<String> paths = <a href="#" class="dart-popover" data-toggle="popov er" title="Remaining arguments" data-html="true" data-trigger="hover focus" data -content="To get the arguments that remain after parsing all of the valid option s and flags, use the rest property.">argResults.rest</a>; | |
264 | |
265 dcat(paths, <a href="#" class="dart-popover" data-toggle="popover" title="Refe r to options and flags by name" data-html="true" data-trigger="hover focus" data -content="You can refer to an option or flag by name treating the ArgResults obj ect like a Map.">argResults[LINE_NUMBER])</a>; | |
266 } | |
267 ... | |
268 </pre> | |
269 | |
270 The | |
271 <a href="https://api.dartlang.org/args.html" target="_blank">API docs</a> | |
272 for the args library | |
273 provide detailed information | |
274 to help you use ArgsParser and ArgResults classes. | |
275 | |
276 ## Reading and writing with stdin, stdout, and stderr {#std-in-out-err} | |
277 | |
278 Like other languages, | |
279 Dart has standard output, standard error, and standard input streams. | |
280 The standard I/O streams are defined at the top level of the dart:io library, | |
281 | |
282 | Stream | Description | | |
283 |---|---| | |
284 | <a href="https://api.dartlang.org/dart_io.html#stdout" target="_blank">stdout< /a> | The standard output | | |
285 | <a href="https://api.dartlang.org/dart_io.html#stderr" target="_blank">stderr< /a> | The standard error | | |
286 | <a href="https://api.dartlang.org/dart_io.html#stdin" target="_blank">stdin</a > | The standard input | | |
287 {: .table } | |
288 | |
289 Import the dart:io library as follows: | |
290 | |
291 {% prettify dart %} | |
292 import 'dart:io'; | |
293 {% endprettify %} | |
294 | |
295 Only command-line applications, not web applications, | |
296 can use the dart:io library. | |
297 | |
298 ### stdout | |
299 | |
300 Here's the code from the `dcat` program that writes the line number to the `stdo ut` | |
301 (if the -n flag is set) followed by the line from the file. | |
302 | |
303 {% prettify dart %} | |
304 if (showLineNumbers) { | |
305 [[highlight]]stdout.write('${lineNumber++} ');[[/highlight]] | |
306 } | |
307 | |
308 [[highlight]]stdout.writeln(line);[[/highlight]] | |
309 {% endprettify %} | |
310 | |
311 The `write()` and `writeln()` methods take an object of any type, | |
312 convert it to a string, and print it. The `writeln()` method | |
313 also prints a newline character. | |
314 `dcat` uses the `write()` method to print the line number so the | |
315 line number and the text appear on the same line. | |
316 | |
317 You can also use the `writeAll()` method to print a list of objects, | |
318 or use `addStream()` to asynchronously print all of the elements from a stream. | |
319 | |
320 `stdout` provides more functionality than the `print()` function. | |
321 For example, you can display the contents of a stream with `stdout`. | |
322 However, you must use `print()` instead of `stdout` | |
323 for programs that are converted to and run in JavaScript. | |
324 | |
325 ### stderr | |
326 | |
327 Use `stderr` to write error messages to the console. | |
328 The standard error stream has the same methods as `stdout`, | |
329 and you use it in the same way. | |
330 Although both `stdout` and `stderr` print to the console, | |
331 their output is separate | |
332 and can be redirected or piped at the command line | |
333 or programmatically to different destinations. | |
334 | |
335 This code from `dcat` prints an error message if the user | |
336 tries to list a directory or if the file is not found. | |
337 | |
338 {% prettify dart %} | |
339 if (isDir) { | |
340 [[highlight]]stderr.writeln('error: $path is a directory');[[/highlight]] | |
341 } else { | |
342 [[highlight]]stderr.writeln('error: $path not found');[[/highlight]] | |
343 } | |
344 {% endprettify %} | |
345 | |
346 ### stdin | |
347 | |
348 The standard input stream typically | |
349 reads data synchronously from the keyboard, | |
350 although it can read asynchronously | |
351 and it can get input piped in from the standard | |
352 output of another program. | |
353 | |
354 Here's a small program that reads a single line from `stdin`: | |
355 | |
356 {% prettify dart %} | |
357 import 'dart:io'; | |
358 | |
359 void main() { | |
360 stdout.writeln('Type something'); | |
361 String input = stdin.readLineSync(); | |
362 stdout.writeln('You typed: $input'); | |
363 } | |
364 {% endprettify %} | |
365 | |
366 The `readLineSync()` method reads text from the standard input stream, | |
367 blocking until the user types in text and presses return. | |
368 This little program prints out the typed text. | |
369 | |
370 In the `dcat` program, | |
371 if the user does not provide a filename on the command line, | |
372 the program instead reads synchronously from stdin | |
373 using the `pipe()` method. | |
374 | |
375 {% prettify dart %} | |
376 return [[highlight]]stdin[[/highlight]].pipe(stdout); | |
377 {% endprettify %} | |
378 | |
379 In this case, | |
380 the user types in lines of text and the program copies them to stdout. | |
381 The user signals the end of input by typing <ctl-d>. | |
382 | |
383 {% prettify bash %} | |
384 $ [[highlight]]dart dcat.dart[[/highlight]] | |
385 [[highlight]]The quick brown fox jumped over the lazy dog.[[/highlight]] | |
386 The quick brown fox jumped over the lazy dog. | |
387 ... | |
388 {% endprettify %} | |
389 | |
390 ## Getting info about a file {#filesystementity} | |
391 | |
392 The | |
393 <a href="https://api.dartlang.org/dart_io/FileSystemEntity.html" target="_blank" >FileSystemEntity</a> | |
394 class in the dart:io library provides | |
395 properties and static methods that help you inspect and manipulate the file syst em. | |
396 | |
397 For example, if you have a path, | |
398 you can determine whether the path is a file, a directory, a link, or not found | |
399 by using the `type()` method from the `FileSystemEntity` class. | |
400 Because the `type()` method accesses the file system, | |
401 it performs the check asynchronously within a Future. | |
402 | |
403 The following code from | |
404 the `dcat` example uses `FileSystemEntity` to determine if the path provided | |
405 on the command line is a directory. | |
406 The Future returns a boolean that indicates | |
407 if the path is a directory or not. | |
408 | |
409 {% prettify dart %} | |
410 [[highlight]]FileSystemEntity.isDirectory(path)[[/highlight]].then((isDir) { | |
411 if (isDir) { | |
412 stderr.writeln('error: $path is a directory'); | |
413 } else { | |
414 stderr.writeln('error: $path not found'); | |
415 } | |
416 exit(2); | |
417 }); | |
418 {% endprettify %} | |
419 | |
420 Other interesting methods in the `FileSystemEntity` class | |
421 include `isFile()`, `exists()`, `stat()`, `delete()`, | |
422 and `rename()`, | |
423 all of which also use a Future to return a value. | |
424 | |
425 FileSystemEntity is the superclass for the File, Directory, and Link classes. | |
426 | |
427 ## Reading a file {#reading-a-file} | |
428 | |
429 `dcat` opens each file listed on the command line | |
430 with the `openRead()` method, | |
431 which returns a stream. | |
432 The `listen()` method registers a callback function that runs | |
433 when data becomes available on the stream. | |
434 The callback function writes that data to stdout. | |
435 | |
436 {% prettify dart %} | |
437 return Future.forEach(paths, (path) { | |
438 int lineNumber = 1; | |
439 Stream<List<int>> stream = new File(path).openRead(); | |
440 | |
441 return stream | |
442 ... | |
443 [[highlight]].listen((line) { | |
444 if (showLineNumbers) { | |
445 stdout.write('${lineNumber++} '); | |
446 } | |
447 stdout.writeln(line); | |
448 })[[/highlight]].asFuture() | |
449 .catchError((_) => _handleError(path)); | |
450 }); | |
451 {% endprettify %} | |
452 | |
453 The following shows the rest of the | |
454 code, which uses two decoders that transform the data before the | |
455 `listen()` callback function runs. | |
456 The UTF8 decoder converts the data into Dart strings. | |
457 `LineSplitter` splits the data at newlines. | |
458 | |
459 {% prettify dart %} | |
460 return Future.forEach(paths, (path) { | |
461 int lineNumber = 1; | |
462 Stream<List<int>> stream = new File(path).openRead(); | |
463 | |
464 return stream | |
465 [[highlight]].transform(UTF8.decoder) | |
466 .transform(const LineSplitter())[[/highlight]] | |
467 .listen((line) { | |
468 if (showLineNumbers) { | |
469 stdout.write('${lineNumber++} '); | |
470 } | |
471 stdout.writeln(line); | |
472 }).asFuture() | |
473 .catchError((_) => _handleError(path)); | |
474 }); | |
475 {% endprettify %} | |
476 | |
477 The dart:convert library contains these and other data converters, including | |
478 one for JSON. | |
479 To use these converters you need to import the dart:convert library: | |
480 | |
481 {% prettify dart %} | |
482 import 'dart:convert'; | |
483 {% endprettify %} | |
484 | |
485 ## Writing a file {#writing-a-file} | |
486 | |
487 The easiest way to write text to a file is to | |
488 create a | |
489 <a href="https://api.dartlang.org/dart_io/File.html" target="_blank">File</a> | |
490 object and use the `writeAsString()` method: | |
491 | |
492 {% prettify dart %} | |
493 File quotesFile = new File('quotes.txt'); | |
494 String stronger = 'That which does not kill us makes us stronger. -Nietzsche'; | |
495 | |
496 quotesFile.writeAsString(stronger, mode: FileMode.APPEND) | |
497 .then((_) { print('Data written.'); }); | |
498 {% endprettify %} | |
499 | |
500 The `writeAsString()` method writes the data asynchronously via a Future. | |
501 It opens the file before writing and closes the file when done. | |
502 To append data to an existing file, you can use the optional | |
503 parameter `mode` and set its value to `FileMode.APPEND`. | |
504 Otherwise, the mode is `FileMode.WRITE` and the previous contents of the file, | |
505 if any, are overwritten. | |
506 | |
507 If you want to write more data, you can open the file for writing. | |
508 The `openWrite()` method returns an IOSink (the same type as stdin and stderr). | |
509 You can continue to write to the file until done, | |
510 at which time, you must close the file. | |
511 The `close()` method is asynchronous and returns a Future. | |
512 | |
513 {% prettify dart %} | |
514 IOSink quotes = new File('quotes.txt').openWrite(mode: FileMode.APPEND); | |
515 | |
516 quotes.write('A woman is like a tea bag; '); | |
517 quotes.write("you never know how strong it is until it's in hot water."); | |
518 quotes.writeln(" -Eleanor Roosevelt"); | |
519 quotes.close().then((_) { print('done'); } ); | |
520 {% endprettify %} | |
521 | |
522 ## Getting environment information {#env-var} | |
523 | |
524 Use the | |
525 <a href="https://api.dartlang.org/dart_io/Platform.html" target="_blank">Platfor m</a> | |
526 class | |
527 to get information about the machine and OS that the program is running on. | |
528 Note: Use the Platform class from the dart:io library, | |
529 not from the dart:html library. | |
530 | |
531 `Platform.environment` provides a copy of the environment | |
532 variables in a mutable map. | |
533 | |
534 {% prettify dart %} | |
535 Map environmentVars = Platform.environment; | |
536 | |
537 print('PWD = ${environmentVars["PWD"]}'); | |
538 print('LOGNAME = ${environmentVars["LOGNAME"]}'); | |
539 print('PATH = ${environmentVars["PATH"]}'); | |
540 {% endprettify %} | |
541 | |
542 `Platform` provides other useful properties that give | |
543 information about the machine, OS, and currently | |
544 running program. | |
545 For example: | |
546 | |
547 * `Platform.isMacOS()` | |
548 * `Platform.numberOfProcessors` | |
549 * `Platform.script.path` | |
550 | |
551 ## Setting exit codes {#exit-codes} | |
552 | |
553 The dart:io library defines a top-level property, | |
554 `exitCode`, that you can change to set the exit code for | |
555 the current invocation of the Dart VM. | |
556 An exit code is a number passed from | |
557 the Dart program to the parent process | |
558 to indicate the success, failure, or other state of the | |
559 execution of the program. | |
560 | |
561 The `dcat` program sets the exit code | |
562 in the `_handleError()` function to indicate that an error | |
563 occcurred during execution. | |
564 | |
565 {% prettify dart %} | |
566 _handleError(String path) { | |
567 FileSystemEntity.isDirectory(path).then((isDir) { | |
568 if (isDir) { | |
569 stderr.writeln('error: $path is a directory'); | |
570 } else { | |
571 stderr.writeln('error: $path not found'); | |
572 } | |
573 [[highlight]]exitCode = 2;[[/highlight]] | |
574 }); | |
575 } | |
576 {% endprettify %} | |
577 | |
578 An exit code of 2 indicates that the program encountered an error. | |
579 | |
580 An alternative to using `exitCode` is to use the top-level `exit()` function, | |
581 which sets the exit code and quits the program immediately. | |
582 For example, the `_handleError()` function could call `exit(2)` | |
583 instead of setting `exitCode` to 2, | |
584 but `exit()` would quit the program | |
585 and it might not process all of the files on the command line. | |
586 | |
587 <aside class="alert alert-info" markdown="1"> | |
588 Generally speaking, you are better off using the `exitCode` property, | |
589 which sets the exit code but allows the program to continue through to its | |
590 natural completion. | |
591 </aside> | |
592 | |
593 Although you can use any number for an exit code, | |
594 by convention, the codes in the table below have the following meanings: | |
595 | |
596 | Code | Meaning | | |
597 |---|---| | |
598 | 0 | Success | | |
599 | 1 | Warnings | | |
600 | 2 | Errors | | |
601 {: .table } | |
602 | |
603 ## Summary {#summary} | |
604 | |
605 This tutorial described some basic API found in these classes from the dart:io l ibrary: | |
606 | |
607 | API | Description | | |
608 |---|---| | |
609 | <a href="https://api.dartlang.org/dart_io/IOSink.html" target="_blank">IOSink< /a> | Helper class for objects that consume data from streams. | | |
610 | <a href="https://api.dartlang.org/dart_io/File.html" target="_blank">File</a> | Represents a file on the native file system | | |
611 | <a href="https://api.dartlang.org/dart_io/Directory.html" target="_blank">Dire ctory</a> | Represents a directory on the native file system | | |
612 | <a href="https://api.dartlang.org/dart_io/FileSystemEntity.html" target="_blan k">FileSystemEntity</a> | Superclass for File and Directory | | |
613 | <a href="https://api.dartlang.org/dart_io/Platform.html" target="_blank">Platf orm</a> | Provides information about the machine and operating system | | |
614 | <a href="https://api.dartlang.org/dart_io.html#stdout" target="_blank">stdout< /a> | The standard output | | |
615 | <a href="https://api.dartlang.org/dart_io.html#stderr" target="_blank">stderr< /a> | The standard error | | |
616 | <a href="https://api.dartlang.org/dart_io.html#stdin" target="_blank">stdin</a > | The standard input | | |
617 | <a href="https://api.dartlang.org/dart_io.html#exitCode" target="_blank">exitC ode</a> | Sets the exit code | | |
618 | <a href="https://api.dartlang.org/dart_io.html#exit" target="_blank">exit()</a > | Sets the exit code and quits | | |
619 {: .table } | |
620 | |
621 In addition, this tutorial covers two classes that help with command-line argume nts: | |
622 | |
623 | Class | Description | | |
624 |---|---| | |
625 | <a href="https://api.dartlang.org/args/ArgParser" target="_blank">ArgParser</a > | A class that transforms a list of raw arguments and into a set of options, f lags, and remaining values. | | |
626 | <a href="https://api.dartlang.org/args/ArgResults" target="_blank">ArgResults< /a> | The result of parsing raw command line arguments using ArgParser. | | |
627 {: .table } | |
628 | |
629 ## Other resources {#other-resources} | |
630 | |
631 Check out the [Command-line Apps Programmers' Guide](/docs/serverguide.html) | |
632 to find more resources related to writing command-line apps. | |
633 | |
634 See the | |
635 [Dartiverse Search walkthrough](/docs/dart-up-and-running/contents/ch05.html) | |
636 for an example of another kind of command-line app: an HTTP server. | |
637 | |
638 Refer to the API docs for <a href="https://api.dartlang.org/dart_io.html" target ="_blank">dart:io</a>, | |
639 <a href="https://api.dartlang.org/dart_async.html" target="_blank">dart:async</a >, | |
640 <a href="https://api.dartlang.org/dart_convert.html" target="_blank">dart:conver t</a>, | |
641 and the | |
642 <a href="https://api.dartlang.org/dart_args.html" target="_blank">args</a> | |
643 package for more classes, functions, and properties. | |
644 | |
645 ## What next? {#what-next} | |
646 | |
647 The [Get Input from a Form](/docs/tutorials/forms/) tutorial | |
648 features a client-server. | |
649 The code for the server, which uses CORS headers and handles | |
650 POST requests, is explained in detail. | |
651 | |
652 {% endcapture %} | |
653 | |
654 {% include tutorial.html %} | |
OLD | NEW |