6

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?

1
  • Maybe you want to check my edit, it gives an easy fast way to craft a byte array
    – EMX
    Commented Aug 21, 2017 at 18:50

2 Answers 2

13

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)
2

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 ]

Not the answer you're looking for? Browse other questions tagged or ask your own question.