show ascii too

This commit is contained in:
AJ ONeal 2017-10-06 20:30:21 -06:00
parent 1efc505490
commit f46266439a
2 changed files with 26 additions and 5 deletions

View File

@ -5,13 +5,19 @@
var hexdump = require('../').hexdump;
var fsname = process.argv[2];
var fs = require('fs');
var opts = {};
if (!fsname || '--help' === fs || '-h' === fs) {
console.error('Usage: hexdump.js <filepath>');
if (!fsname || '--help' === fsname || '-h' === fsname) {
console.error('Usage: hexdump.js -C <filepath>');
process.exit(2);
return;
}
if ('-C' === fsname) {
opts.C = true;
fsname = process.argv[3];
}
try {
fs.statSync(fsname);
} catch(e) {
@ -21,7 +27,7 @@ try {
}
var nb = fs.readFileSync(fsname);
var str = hexdump(nb.buffer, nb.byteOffset, nb.byteLength);
var str = hexdump(nb.buffer, nb.byteOffset, nb.byteLength, opts);
console.log(str);
}());

View File

@ -1,7 +1,8 @@
(function (exports) {
'use strict';
exports.hexdump = function hexdump(ab, offset, len) {
exports.hexdump = function hexdump(ab, offset, len, opts) {
if (!opts) { opts = {}; }
var ui8 = new Uint8Array(ab.buffer || ab, offset || ab.byteOffset, len || ab.byteLength);
var bytecount = 0;
var head = ' 0 1 2 3 4 5 6 7 8 9 A B C D E F';
@ -20,7 +21,21 @@ exports.hexdump = function hexdump(ab, offset, len) {
lead = '0' + lead;
}
return lead + ' ' + str;
while (str.length < 48) {
str += ' ';
}
if (opts.C) {
return lead + ' ' + str + ' |' + str.replace(/ /g, '').match(/.{1,2}/g).map(function (ch) {
var c = String.fromCharCode(parseInt(ch, 16));
if (!/[ -~]/.test(c)) {
c = '.';
}
return c;
}).join('') + '|';
} else {
return lead + ' ' + str;
}
}).join('\n');
trail = (len || ab.byteLength).toString(16);