1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-27 01:29:14 -05:00
denoland-deno/docs/examples/unix_cat.md

37 lines
1 KiB
Markdown
Raw Normal View History

2020-09-12 08:03:18 -04:00
# An implementation of the unix "cat" program
## Concepts
- 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
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
handle to a file.
2020-09-12 08:03:18 -04:00
- [Deno.copy](https://doc.deno.land/builtin/stable#Deno.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
- 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
*/
2020-05-06 18:21:13 -04:00
for (let i = 0; i < Deno.args.length; i++) {
2020-06-08 18:52:23 -04:00
const filename = Deno.args[i];
const file = await Deno.open(filename);
2020-05-06 18:21:13 -04:00
await Deno.copy(file, Deno.stdout);
file.close();
}
```
2020-09-12 08:03:18 -04:00
To run the program:
2020-05-06 18:21:13 -04:00
```shell
deno run --allow-read https://deno.land/std@$STD_VERSION/examples/cat.ts /etc/passwd
2020-05-06 18:21:13 -04:00
```