Buffers
Pure JavaScript is Unicode friendly, but it is not so for binary data.
While dealing with TCP streams or the file system, it's necessary to handle octet streams.
Node provides
Buffer class
which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.Buffer class
is a global class that can be accessed in an application without importing the buffer module
1. Creating Buffers
Node Buffer can be constructed in a variety of ways!
Method 1
Create an uninitiated
Buffer
of 10 octets
Method 2
Create a
Buffer
from a given array
Method 3
Create a
Buffer
from a given string and optionally encoding type
2. Writing to Buffers
Syntax
Parameters
string
string data
to be written to buffer
offset
index
of the buffer to start writing atdefault value is
0
length
number of bytes to write
defaults to
buffer.length
encoding
encoding to use
default is
utf8
Return Value
: .write()
은 쓰여진 octet 의 수를 return 한다
ex)
buffer_write.js
Result
3. Reading from Buffers
Syntax
Parameters
encoding
encoding to use
default is
utf8
start
beginning index to start reading
defaults is to
0
end
end index to end reading
default is
complete buffer
Return Value
: toString
은 encoding 된 buffer data를 지정한 character set으로 return 한다!
ex)
buffer_toString.js
4. Convert Buffer to JSON
Syntax
Return Value
: Buffer instance를 JSON
형식으로 return 한다!
ex)
buffer_toJSON.js
result
5. Concatenate Buffers
Syntax
Parameters
list
Array List of Buffer objects to be concatenated.
totalLength
This is the total length of the buffers when concatenated.
Return Value
: .concat()
은 Buffer instance를 return 한다
ex)
buffer_concat.js
Result
Compare Buffers
Syntax
Parameters
otherBuffer
위의 syntax 예시에서
buf
와 비교할 다른 buffer
Return Value
buf
과otherBuffer
를 비교할 때같으면 return
0
sort 한 후
otherBuffer
가buf
보다 더 앞에 오면1
sort 한 후
otherBuffer
가buf
보다 더 뒤에 오면-1
ex)
buffer_compare.js
Result
Copy Buffer
Syntax
Parameters
targetBuffer
Buffer object where buffer will be copied.
targetStart
Number, Optional
Default:
0
sourceStart
Number, Optional
Default:
0
sourceEnd
Number, Optional
Default:
buffer.length
Return Value
: return 값 없음~!
ex)
buffer_copy.js
Result
Slice Buffer
Syntax
Parameters
start − Number, Optional, Default: 0
end − Number, Optional, Default: buffer.length
Return Value
Returns a new buffer which references the same memory as the old one, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
ex)
buffer_slice.js
Result
Last updated