Generate and write binary data to a stream in Node.js

I want to generate some binary data in my Node.js application and then write it in an HTTP response to be downloaded by the client. My current implementation of the same application is in Python , which achieves this using struct. For instance,

import struct
# ...
s = 'Filename header'
s_binary = struct.pack('15s',s)
# ...

Also, how to convert numbers to binary files in Node.js? How I do it in Python:

# To convert a float into four byte binary representation in Python.
import struct
num_binary = struct.pack('f',23.33)

How do I do the same in Node.js?

This is the best solution I have - the direct port of the Python struct library for Node.js is jspack .

+3
source share
2 answers

You can watch Bison . This is similar to JSON, but creates binary data.

+1
source
var s="Filename header";
var s_binary=new Buffer(15);
for(var i=0;i<s_binary.length;i++) {
    s_binary[i]=0;
}
s_binary.write(s);
// Now you can write s_binary to a stream.
+1
source

Source: https://habr.com/ru/post/1788380/


All Articles