Buffer 是 Node.js 處理二進位資料的核心。而要把一段字串寫入 Buffer,就得靠 buffer.write。
它會將 string 依指定的 encoding 編碼後,寫入到 buffer 的 offset 位置,並回傳實際寫入了多少個位元組。
若 Buffer 的剩餘空間不足以容納整個 string,則只會寫入能放得下的部分。
buffer.write(string, [offset], [length], [encoding])
buf = new Buffer(256);
len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
原始碼中可看到它做了相當完整的參數相容處理,能同時支援 write(string, encoding)、write(string, offset, length, encoding) 等多種呼叫形式,並依編碼分派到對應的底層寫入函式:
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;
}
}
var remaining = this.length - offset;
if (util.isUndefined(length) || length > remaining)
length = remaining;
encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
// ... 依編碼分派至 hexWrite / utf8Write / asciiWrite 等
return ret;
};
掌握 write,你就能在 Buffer 上精準地堆放各類資料了。