파일의 헤더를 검출할 목적으로 공부해본 내용을 바탕으로 헥사 코드 일부분을 읽어오는 코드를 작성하여 보았다.
/**
* hex_viewer.js
*/
const { print } = require("./_system");
const fs = require('fs');
const sf = require("sf");
//const filename = process.argv[2];
/**
* filename : file PATH + file name
* end : read count, 2^n - 1, not 0
*/
function getArrayByStream(filename, end){
let hexData = [];
const readStream = fs.createReadStream(filename, { highWaterMark : 1, end});
return new Promise((resolve, reject)=>{
readStream.on('data', (chunk) => {
/*
hexData.push(sf("{0:x2}{1:x2} {2:x2}{3:x2} {4:x2}{5:x2} {6:x2}{7:x2} {8:x2}{9:x2} {10:x2}{11:x2} {12:x2}{13:x2} {14:x2}{15:x2}",
chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
chunk[8], chunk[9], chunk[10], chunk[11], chunk[12], chunk[13], chunk[14], chunk[15]));
*/
hexData.push(sf("{0:x2} \`{1}\`", chunk[0], String.fromCharCode(chunk[0])));
});
readStream.on('end', () => {
resolve(hexData);
});
readStream.on('error', (error) => {
reject(error);
});
});
}
/**
* filename : file PATH + file name
* end : read count, 2^n - 1, not 0
*/
function view(filename, end){
getArrayByStream(filename, end).then((data) => {
//print(data.toString().replace(/,/gm,'='));
data.forEach(element => {
print(`${element}`);
});
}).catch(error => {
console.error(error);
});
}
module.exports = {
getArrayByStream,
view,
}