updated on Thu Jan 12 20:00:29 UTC 2012
[aur-mirror.git] / hexutils / hexutils.js
blob38c5d8168f74845ea091e4972e217d9180d90766
1 var fs = require("fs");
3 var buffer_to_hex = function(data) {
4     var output = "";
6     for(var i=0; i<data.length; i++) {
7         var c = data[i].toString(16);
9         while(c.length < 2) {
10             c = "0" + c;
11         }
13         output += c;
14     }
16     return output;
19 var buffer_from_hex = function(data) {
20     var buf = new Buffer(data.length / 2);
22     for(var i=0; i<data.length; i++) {
23         var c = "" + data[i*2] + data[(i*2)+1];
24         c = parseInt(c, 16);
25         buf[i] = c;
26     }
28     return buf;
31 function help() {
32     console.log("Usage: hexutils [OPTION] [INFILE] [OUTFILE]");
33     console.log("Convert hex string to characters or vice versa");
34     console.log();
35     console.log("  -h, --hex   Convert characters to hex string");
36     console.log("  -c, --char  Convert hex string to characters");
37     console.log();
38     console.log("With no INFILE and OUTFILE, or when INFILE is -, read standard input.");
39     console.log("With no OUTFILE, or when OUTFILE is -, write to standard output.");
40     console.log();
41     console.log("Report bugs to <steve@offend.me.uk>.");
44 if(process.argv.length < 3) {
45         help();
46     process.exit();
49 var mode = null;
50 if(process.argv[2] == "-h" || process.argv[2] == "--hex") {
51     mode = "hex";
52 } else if(process.argv[2] == "-c" || process.argv[2] == "--char") {
53     mode = "char";
54 } else {
55     help();
56     process.exit();
59 var instream, outstream = null;
60 if(process.argv.length < 4 || process.argv[3] == "-") {
61     instream = process.stdin;
62     if(mode == "char") {
63         process.stdin.setEncoding("utf8");
64     }
65     process.stdin.resume();
66 } else {
67     instream = fs.createReadStream(process.argv[3], {
68         encoding: (mode == "char" ? "utf8" : null)
69     });
72 if(process.argv.length < 5 || process.argv[4] == "-") {
73     outstream = process.stdout;
74     process.stdout.setEncoding("utf8");
75 } else {
76     outstream = fs.createWriteStream(process.argv[4]);
79 function convert(data) {
80     return (mode == "hex" ? buffer_to_hex(data) : buffer_from_hex(data));
83 instream.on("error", function(err) {
84     console.error("Error reading input");
85     process.exit();
86 });
88 outstream.on("error", function(err) {
89     console.error("Error writing output");
90     process.exit();
91 });
93 instream.on("data", function(data) {
94     try {
95         data = convert(data);
96     } catch(err) {
97         console.error("Failed to encode");
98         process.exit();
99     }
101     outstream.write(data);
104 instream.on("end", function(data) {
105     outstream.end();