0

I have a binary data in c++ variable buffer as below:

int len = 39767;
uint16_t * buffer = (uint16_t) malloc(len);
FILE * fp = fopen("rahul.jpg", "rb"); // size of file is 39767 byte.
fread(buffer, len, 1, fp);
fclose(fp);
fp = fopen("rahul3.jpg", "wb");
fwrite(buffer, len, 1, fp);  // Here it is written correct.
fclose(fp);

I want to pass this buffer to Node.js and write to a file. I used below line to convert it to Local and then wrapping to an Object:

Local<String> str = Nan::New(buffer).ToLocalChecked();
return scope.Escape(str);

But, in node.js when I am checking length of received data it prints 9 only and value seems corrupted.

console.log(data);
console.log("len = " + data.length );
fs.writeFileSync('rahul2.jpg', data, 'binary');

Here rahul2.jpg is corrupted and is of 9 bytes only. How can we get rahul2.jpg from node.js code same as rahul.jpg in c++? Which Nan::New() we should use to pass binary data unaffected? Please help. Thanks.

ZachB
  • 13,051
  • 4
  • 61
  • 89
Bimal Jha
  • 391
  • 2
  • 14
  • I suppose, `ToLocalChecked()` provide a string, and some conversion of data is performed. So consider posibilities of data specification for `New` or use other method insted this – VolAnd Jun 30 '16 at 17:08
  • Try `Nan::NewBuffer()` – VolAnd Jun 30 '16 at 17:22
  • After applying CopyBuffer(), I can see data in node.js as of 10 bytes only. How can I get rahul2.jpg same as rahul.jpg? Thanks. – Bimal Jha Jun 30 '16 at 19:11

2 Answers2

0

Try something like this:

   Local<Value> returnValue = Nan::CopyBuffer(buffer, len).ToLocalChecked();

and, by the way, fread returns the number of bytes read from file, so it is better to do as follows:

   int truelen = fread(buffer, len, 1, fp);
   . . .
   fwrite(buffer, truelen, 1, fp);
VolAnd
  • 6,367
  • 3
  • 25
  • 43
0

Local<String> str = Nan::NewOneByteString((uint8_t *) buffer, len).ToLocalChecked();

I used above code in C++ which solved the issue. In node.js used the below code to write to file: fs.writeFileSync('rahul2.jpg', data, 'binary');

Thanks.

Bimal Jha
  • 391
  • 2
  • 14