Node.js Buffer.toString() 方法详解与源码解析

作者:慢半拍时间:2026-10-28 17:35:56浏览:523

本文详细介绍Node.js中Buffer对象的toString()方法,涵盖其将缓冲区数据转换为指定编码字符串的功能。文章解析了encoding、start和end三个参数的默认值与用法,并通过示例展示base64编码转换。此外,深入剖析了该方法的底层源码实现,包括编码类型判断、边界处理及大小写兼容逻辑,帮助开发者理解其工作机制。

Buffer.toString() 方法概述

本节介绍Buffer对象提供的toString()方法。

该方法用于将Buffer实例中的数据转换为指定字符编码的字符串形式。

以下是该方法的语法定义。

具体调用方式如下:

buffer.toString([encoding], [start], [end])

该方法接收以下参数:

encoding:指定转换后的字符串字符编码,默认值为 'utf8'。

start:指定缓冲区转换的起始字节索引,默认值为 0。

end:指定缓冲区转换的结束字节索引,默认值为Buffer对象的长度。

以下是一个简单的使用示例。

示例代码如下:

var b = new Buffer(50);
 
console.log(b);
 
var c = b.toString('base64',0,10);
 
console.log(c);

源码实现与逻辑分析

接下来查看该方法的底层源码实现。

源码实现如下:

// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function(encoding, start, end) {
var loweredCase = false;
start = start >>> 0;
end = util.isUndefined(end) ? this.length : end >>> 0;
if (!encoding) encoding = 'utf8';
if (start < 0) start = 0;
if (end > this.length) end = this.length;
if (end <= start) return '';
while (true) {
switch (encoding) {
case 'hex':
return this.hexSlice(start, end);
case 'utf8':
case 'utf-8':
return this.utf8Slice(start, end);
case 'ascii':
return this.asciiSlice(start, end);
case 'binary':
return this.binarySlice(start, end);
case 'base64':
return this.base64Slice(start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return this.ucs2Slice(start, end);
default:
if (loweredCase)
throw new TypeError('Unknown encoding: ' + encoding);
encoding = (encoding + '').toLowerCase();
loweredCase = true;
    }
  }
};
作者最新文章