nodejs,如何判断是buffer还是string?buffer和string如何互转
发布于 作者:苏南大叔 来源:程序如此灵动~

Buffer
是nodejs
特有的数据类型,本文的代码在浏览器下是无法运行的。本文的代码仅仅适用于普通的nodejs
。本文主要讨论如何判断是否是buffer
,buffer
和string
如何相互转化。
苏南大叔的程序如此灵动博客,记录苏南大叔和计算机代码的故事。测试环境:node@16.14.2
。
字符串和buffer
互转
let buf = Buffer.from('字符串');
let str = buf.toString('utf-8');
Buffer
类型判断
推荐使用:
Buffer.isBuffer(buf);
过时的表述:
let util = require('util');
util.isBuffer(buf);
String
类型判断
推荐使用:
typeof str === 'string'
过时的表述:
let util = require('util');
util.isString(data);
测试代码
let util = require('util');
let data = Buffer.from('苏南大叔说:hola');
console.log(data);
if (Buffer.isBuffer(data)) {
console.log(util.isBuffer(data));
console.log("是buffer,进行转换:");
data = data.toString('utf-8');
}
console.log(data);
if (typeof data === 'string') {
console.log("另外一个过时的判断方法:");
console.log(util.isString(data));
}
相关链接
- https://newsn.net/say/js-type.html
- https://newsn.net/say/js-arr-shift.html
- https://newsn.net/say/js-arr-find.html
结束语
更多nodejs
相关文章,请点击:


