3

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
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.

10 Comments

ok this might work. Do you know how to convert numbers into binary? Let me update the question with an example in python.
good solution. Except you don't need to fill with nulls if you're going to immediately fill the buffer with text.
you can write buffers to streams, eg from the http example, you can do res.end(myBuffer). To send only the first 8 bytes of the buffer: res.end(myBuffer.slice(0, 8));
@JasonWoof: Actually, it is necessary. The Python code will pad the string with null bytes if the string is less than 15 characters. If left uninitialized in node.js, it will be full of junk bytes.
but it's not less than 15 characters
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.