Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating and writing binary data to stream in Node.js

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

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

Also, how do I convert numbers into binary in Node.js? The way I do it in Python is:

# 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 thing in Node.js?

This is so far the best solution I've got - straight port of Python's struct library to Node.js - jspack.

like image 240
Jayesh Avatar asked Jun 02 '26 23:06

Jayesh


2 Answers

You can look at Bison. It's like JSON but creates binary data.

like image 174
Raynos Avatar answered Jun 06 '26 03:06

Raynos


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.
like image 42
icktoofay Avatar answered Jun 06 '26 02:06

icktoofay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!