UNPKG

1.78 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3/* All of the following commands are equivalent and write `foo\tbar foo` to out.txt
4 $ ./echo.js -n -e --output=out.txt "foo\tbar" "foo"
5 $ ./echo.js --newline --escape --output "out.txt" "foo\tbar" "foo"
6 $ ./echo.js -ne --output=out.txt "foo\tbar" "foo"
7 $ ./echo.js -en --output="out.txt" "foo\tbar" "foo"
8*/
9
10var cli = require('cli');
11
12cli.parse({
13 newline: ['n', 'Do not output the trailing newline'],
14 escape: ['e', 'Enable interpretation of backslash escapes'],
15 separator: ['s', 'Separate arguments using this value', 'string', ' '],
16 output: [false, 'Write to FILE rather than the console', 'file']
17});
18
19cli.main(function (args, options) {
20 var output = '', i, j, l, output_stream;
21
22 if (this.argc) {
23 if (options.escape) {
24 var replace = {'\\n':'\n','\\r':'\r','\\t':'\t','\\e':'\e','\\v':'\v','\\f':'\f','\\c':'\c','\\b':'\b','\\a':'\a','\\\\':'\\'};
25 var escape = function (str) {
26 string += '';
27 for (j in replace) {
28 string = string.replace(i, replace[i]);
29 }
30 return string;
31 }
32 for (i = 0, l = this.argc; i < l; i++) {
33 args[i] = escape(args[i]);
34 }
35 options.separator = escape(options.separator);
36 }
37 output += args.join(options.separator);
38 }
39
40 if (!options.newline) {
41 output += '\n';
42 }
43
44 try {
45 if (options.output) {
46 output_stream = this.native.fs.createWriteStream(options.output)
47 } else {
48 output_stream = process.stdout;
49 }
50 output_stream.write(output);
51 } catch (e) {
52 this.fatal('Could not write to output stream');
53 }
54});
\No newline at end of file