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
Was this helpful?