This article mainly introduces node. buffer in js. description of the write method. This article introduces the buffer. write method description, syntax, receive parameters, use instances, and implement Source Code. For more information, see
Method description:
Write string into the buffer offset using the specified encoding.
Returns the number of octal bytes written.
If the Buffer does not have enough space to adapt to the entire string, only the part of the string will be written.
Syntax:
The Code is as follows:
Buffer. write (string, [offset], [length], [encoding])
Receiving parameters:
String String, the data written into the buffer.
Offet number (Optional). The default value is 0. The location where data is written to the buffer.
Length Number, optional. Default Value: buffer. length-offset. The length of data to be written.
Encoding String, the encoding format required. Optional. The default value is "utf8 ″.
Example:
The Code is as follows:
Buf = new Buffer (1, 256 );
Len = buf. write ('\ u00bd + \ u00bc = \ u00be', 0 );
Console. log (len + "bytes:" + buf. toString ('utf8', 0, len ));
Source code:
The Code is as follows:
Buffer. prototype. write = function (string, offset, length, encoding ){
// Allow write (string, encoding)
If (util. isString (offset) & util. isUndefined (length )){
Encoding = offset;
Offset = 0;
// Allow write (string, offset [, length], encoding)
} Else if (isFinite (offset )){
Offset = ~~ Offset;
If (isFinite (length )){
Length = ~~ Length;
} Else {
Encoding = length;
Length = undefined;
}
// XXX legacy write (string, encoding, offset, length)-remove in v0.13
} Else {
If (! WriteWarned ){
If (process. throwDeprecation)
Throw new Error (writeMsg );
Else if (process. traceDeprecation)
Console. trace (writeMsg );
Else
Console. error (writeMsg );
WriteWarned = true;
}
Var swap = encoding;
Encoding = offset;
Offset = ~~ Length;
Length = swap;
}
Var remaining = this. length-offset;
If (util. isUndefined (length) | length> remaining)
Length = remaining;
Encoding = !! Encoding? (Encoding + ''). toLowerCase (): 'utf8 ';
If (string. length> 0 & (length <0 | offset <0 ))
Throw new RangeError ('attempt to write beyond buffer bounds ');
Var ret;
Switch (encoding ){
Case 'hex ':
Ret = this. hexWrite (string, offset, length );
Break;
Case 'utf8 ':
Case 'utf-8 ':
Ret = this. utf8Write (string, offset, length );
Break;
Case 'ascii ':
Ret = this. asciiWrite (string, offset, length );
Break;
Case 'binary ':
Ret = this. binaryWrite (string, offset, length );
Break;
Case 'base64 ':
// Warning: maxLength not taken into account in base64Write
Ret = this. base64Write (string, offset, length );
Break;
Case 'ucs2 ':
Case 'ucs-2 ':
Case 'utf16le ':
Case 'utf-16le ':
Ret = this. ucs2Write (string, offset, length );
Break;
Default:
Throw new TypeError ('unknown encoding: '+ encoding );
}
Return ret;
};