Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronously read file and convert to byte-array

I'm using Node.js to gzip some files and output their raw byte array to a file.

For example:

test.txt:

1234

text.txt > test.txt.gz

test.txt.gz to byte array > array.txt

array.txt:

{0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e}


I couldn't seem to find any other questions on converting files to byte-arrays, or any npm packages. I have attempted to manually fs.readFileSync a file and use it in a function, but due to the special characters and encoding it failed.

How can I convert a file to a byte array in Node.js natively or using a package?

like image 625
Sam Denty Avatar asked Dec 24 '22 14:12

Sam Denty


2 Answers

I think this accomplishes what you want, albeit a bit dirty.

FYI: fs.readFileSync returns a Buffer object, which you can convert to hex via Buffer.toString('hex')

var fs = require('fs');

function getByteArray(filePath){
    let fileData = fs.readFileSync(filePath).toString('hex');
    let result = []
    for (var i = 0; i < fileData.length; i+=2)
      result.push('0x'+fileData[i]+''+fileData[i+1])
    return result;
}

result = getByteArray('/path/to/file')
console.log(result)
like image 96
Michael Ward Avatar answered Dec 28 '22 10:12

Michael Ward


example :

console.log("[string]:")
const _string = 'aeiou.áéíóú.äëïöü.ñ';
console.log(_string)

console.log("\n[buffer]:")
const _buffer = Buffer.from(_string, 'utf8');
console.log(_buffer)

console.log("\n[binaryString]:")
const binaryString = _buffer.toString();
console.log(binaryString)

output :

[string]:
aeiou.áéíóú.äëïöü.ñ

[buffer]:
<Buffer 61 65 69 6f 75 2e c3 a1 c3 a9 c3 ad c3 b3 c3 ba 2e c3 a4 c3 ab c3 af c3 b6 c3 bc 2e c3 b1>

[binaryString]:
aeiou.áéíóú.äëïöü.ñ

EDIT: EASY WITH convert-string

example :

console.log("[string]:")
const _string = 'aeiou.áéíóú.äëïöü.ñ';
console.log(_string)

console.log("\n[byteArray]:")
const converter = require('convert-string')
const byteArray = converter.UTF8.stringToBytes(_string)
console.log(byteArray)

output:

[byteArray]:
[ 97,
  101,
  105,
  111,
  117,
  46,
  195,
  161,
  195,
  169,
  195,
  173,
  195,
  179,
  195,
  186,
  46,
  195,
  164,
  195,
  171,
  195,
  175,
  195,
  182,
  195,
  188,
  46,
  195,
  177 ]
like image 45
EMX Avatar answered Dec 28 '22 11:12

EMX