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