Saving raw data (AD 25 D9...) as a binary file

I'm building a simple app that allows me to read photo data from serial port in node.js.

Everything works fine except I'm getting raw bytes in node.js. The question is how to save this data (AD 25 D9 0B DC DE E7 FF D9 ...) as a binary JPEG file (since it is a photo)?

Thanks in advance!

I assume you are streaming the data. That is, you have to detect an magic number indicating the beginning of the actual JPEG file, and the EOI (End-Of-Image) magic-number.

We're looking for 2 bytes. When receiving the sequence (magic number of JPEG), the image began streaming onto the application – finally, as the application detects (magic number of end of JPEG), the image has successfully been transferred.

As you didn't specify how you transfer your data, I assume you have something similar to the following somewhere in your code.

stream.on("data", function (chunk) { });

You might want to briefly check for the magic number by stacking the bytes in order of they streamed onto the server.

You now have the following:

  • Let the server detect the initiat identifier of the JPEG: detect, if an byte String.fromCharCode(0xFF) is being followed by a String.fromCharCode(0xD8) byte (those bytes are written to the disk, too!)
  • Stream the data onto the hard-disk
  • While streaming onto the hard-disk, let the server be aware of the data: detect, if a byte String.fromCharCode(0xFF) is followed by a String.fromCharCode(0xD9) byte.

Be aware, that any byte-sequence <0xFF, 0xD8> signalizes an image. So every time this occurs, data is being written.