2020-09-12 08:03:18 -04:00
|
|
|
# An implementation of the unix "cat" program
|
|
|
|
|
|
|
|
## Concepts
|
|
|
|
|
2020-09-27 13:49:41 -04:00
|
|
|
- Use the Deno runtime API to output the contents of a file to the console.
|
2020-09-12 08:03:18 -04:00
|
|
|
- [Deno.args](https://doc.deno.land/builtin/stable#Deno.args) accesses the
|
2020-09-27 13:49:41 -04:00
|
|
|
command line arguments.
|
2020-09-12 08:03:18 -04:00
|
|
|
- [Deno.open](https://doc.deno.land/builtin/stable#Deno.open) is used to get a
|
2020-09-27 13:49:41 -04:00
|
|
|
handle to a file.
|
2021-07-12 13:44:42 -04:00
|
|
|
- [copy](https://doc.deno.land/https/deno.land/std@$STD_VERSION/io/util.ts#copy)
|
|
|
|
is used to transfer data from the file to the output stream.
|
2020-09-12 08:03:18 -04:00
|
|
|
- Files should be closed when you are finished with them
|
2020-09-27 13:49:41 -04:00
|
|
|
- Modules can be run directly from remote URLs.
|
2020-09-12 08:03:18 -04:00
|
|
|
|
|
|
|
## Example
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
In this program each command-line argument is assumed to be a filename, the file
|
2020-09-12 08:03:18 -04:00
|
|
|
is opened, and printed to stdout (e.g. the console).
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
```ts
|
2020-09-12 08:03:18 -04:00
|
|
|
/**
|
|
|
|
* cat.ts
|
|
|
|
*/
|
2021-07-12 13:44:42 -04:00
|
|
|
import { copy } from "https://deno.land/std@$STD_VERSION/io/util.ts";
|
2021-05-05 00:07:08 -04:00
|
|
|
for (const filename of Deno.args) {
|
2020-06-08 18:52:23 -04:00
|
|
|
const file = await Deno.open(filename);
|
2021-07-12 13:44:42 -04:00
|
|
|
await copy(file, Deno.stdout);
|
2020-05-06 18:21:13 -04:00
|
|
|
file.close();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-09-12 08:03:18 -04:00
|
|
|
To run the program:
|
2020-05-06 18:21:13 -04:00
|
|
|
|
|
|
|
```shell
|
2020-07-31 05:12:20 -04:00
|
|
|
deno run --allow-read https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/passwd
|
2020-05-06 18:21:13 -04:00
|
|
|
```
|