Friday, 12 October 2012

[NodeJS] Write bytes to a file

Description
The idea is to get a buffer of bytes from a socket or a file, and then convert them into a file, you can thinking about to transfer an image through a socket, that is my case.

Buffer library
NodeJS has a library buffer that takes care to convert decimal to hex, and then you can use it to write into a file. In my case, I have to convert decimal to hex but you can even populate the buffer with only hex values.

This is a piece of code to write into a file:

var Buffer = require('buffer').Buffer;
var fs = require('fs');


var myBuffer= new Buffer(3);
myBuffer[0] = 71;
myBuffer[1] = 73;
myBuffer[2] = 70;

console.log(test);


fs.writeFile("test.txt", test, function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

Your output should be something like that:

<Buffer 47 49 46>

means that your values has been converted into bytes, from decimal to hex, you can check it with a Calculator.
Also you should get the message "The file was saved!" and then if you check what there is inside, you have to read "GIF".

That is all you need to convert your buffer of bytes into a file, image, text, etc...

2 comments:

  1. Oh thanks! Always dreamed about this solution! THANK YOU CHRISTIAN FROM SWITZERLAND!

    ReplyDelete
  2. Yeah! Thank you very much for your interesting article! ;)

    ReplyDelete