1 var fs
= require("fs");
3 var buffer_to_hex = function(data
) {
6 for(var i
=0; i
<data
.length
; i
++) {
7 var c
= data
[i
].toString(16);
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];
32 console
.log("Usage: hexutils [OPTION] [INFILE] [OUTFILE]");
33 console
.log("Convert hex string to characters or vice versa");
35 console
.log(" -h, --hex Convert characters to hex string");
36 console
.log(" -c, --char Convert hex string to characters");
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.");
41 console
.log("Report bugs to <steve@offend.me.uk>.");
44 if(process
.argv
.length
< 3) {
50 if(process
.argv
[2] == "-h" || process
.argv
[2] == "--hex") {
52 } else if(process
.argv
[2] == "-c" || process
.argv
[2] == "--char") {
59 var instream
, outstream
= null;
60 if(process
.argv
.length
< 4 || process
.argv
[3] == "-") {
61 instream
= process
.stdin
;
63 process
.stdin
.setEncoding("utf8");
65 process
.stdin
.resume();
67 instream
= fs
.createReadStream(process
.argv
[3], {
68 encoding
: (mode
== "char" ? "utf8" : null)
72 if(process
.argv
.length
< 5 || process
.argv
[4] == "-") {
73 outstream
= process
.stdout
;
74 process
.stdout
.setEncoding("utf8");
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");
88 outstream
.on("error", function(err
) {
89 console
.error("Error writing output");
93 instream
.on("data", function(data
) {
97 console
.error("Failed to encode");
101 outstream
.write(data
);
104 instream
.on("end", function(data
) {