Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  166] [ 2]  / answers: 1 / hits: 19701  / 7 Years ago, mon, august 21, 2017, 12:00:00

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?


More From » arrays

 Answers
7

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)

[#56694] Friday, August 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandt

Total Points: 43
Total Questions: 90
Total Answers: 111

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
;