buffer (Binary data storage module)
Used to handle raw binary data (can be text in utf8 or jpeg or anything), heavily used when working with files and receiving data from <input type="file">.
Please keep in mind, as of 21 century, most text files are utf8 encoded, while String objects in javascript are internally stored in utf-16, hence conversion is needed while working with files, writting data to stdout or anything else.
Usage:
var buffer=require("buffer");
Working with buffer:
var buffer=require("buffer");
var fs=require("fs");
// Reading contents of /etc/passwd and storing it as a String
var f2=new fs.File("/etc/passwd");
f2.open("r");
var contents=f2.read().toString("utf-8");
f2.close();
// Creating Buffer object filled with zeroes (100 bytes)
var zeroes100=new buffer.Buffer(100,0);
var f3=new fs.File("/tmp/zeroes-100.bin");
f3.open("w");
f3.write(zeroes100);
f3.close();
// Filling zeroes100 object with bytes 0..99
for (var i=0;i<zeroes100.length;i++) zeroes100[i]=i;
// Creating a new Buffer object containing a part of zeroes100 object data
var part=zeroes100.slice(20,40);
// contains bytes [20,21 .... 39]
var f3=new fs.File("/tmp/filled-20-39.bin");
f3.open("w");
f3.write(part);
f3.close();
Accepting <input type="file"> from http request:
var fs=require("fs");
// <input type="file" name="myjpeg">
var data=request.post.files.myjpeg.data;
var f1=new fs.File("/tmp/myfile.jpg");
f1.open("w");
f1.write(data);
f1.close();
List of methods of Buffer class
Name | Arguments | Returns | Description |
---|---|---|---|
new | Buffer src | Creates an object of Buffer class, copying data from another Buffer. | |
new | int length | Creates an object of Buffer class, size length bytes, filled with 0 | |
new | int length, int fill | Creates an object of Buffer class, size length bytes, filled with fill (byte). | |
new | String src | Creates an object of Buffer class, with src converted to utf-8 encoding. | |
toString | String enc | String | Returns Strings, converted from encoding enc. Throws exception if cannot convert from encoding. |
range | int first, int last | Buffer | Returns an object of Buffer class, copied from byte first to byte last (not including). Throws exception if indexes are incorrect. |
slice | same (deprecated?) | ||
fill | int fill, int first, int last | Fills a part of binary data with fill (byte). | |
copy | Array dst, int off_t, int off_s, int len | ||
copy | Buffer dst, int off_t, int off_s, int len | ||
copyFrom | Array src, int off_s, int off_t, int len | ||
copyFrom | Buffer src, int off_s, int off_t, int len | ||
read | Not implemented yet | ||
write | Not implemented yet |
List of properties of Buffer class
Name | Arguments | Returns | Description |
---|---|---|---|
length | int | Returns buffer size, in bytes. | |
[] | int pos | int | Getter, Setter for byte value at position pos |