[Node.js] Node.js Buffers
>> node >>fs.readFile('finnish.txt', function(err,data){ console.log(data); }); // Output string is not what we want >>fs.readFile('finnish.txt', function(err, data){ console.log(data.toString()); }); // Ouptu is ok /* Encoding */ >>fs.readFile('finnish.txt', 'utf8', function(err,data){ console.log(data); }); // Ouptu is ok >>str = '\u0048\u0065\u006c\u006f \u0057\u006f\u0072\u006c\u0064\u0021'; 'Hello World' str.length 12 Buffer.byteLength(str, 'utf8') 12 But the Buffer.byteLength and str.length are not equal!! ------ >>str = '\u00bd + \u00bc = \u00be'; '1/2 + 1/4 = 3/4'; str.length 9 Buffer.byteLength(str, 'utf8') 12 ----- >>buf = new Buffer(5) >>buf.write('hello wolrd'); >>buf.toString() 'hello' >>buf.write('hello', 2); hehel >>buf.write('xxxx', 2, 1); >>buf.toString() hexel >>buf.write('xxxx', 2, 2); >>buf.toString() hexxel >>buf.write('yyyy', 2, 1, 'utf8') >>buf.toString() heyel ----- buf1 = new Buffer('1234') buf2 = new Buffer('0123') buf3 = new Buffer('1234') buf1.compare(buf2) 1 //not equal buf1.compare(buf3) 0 //equal buf1.equals(buf2) false >>var arr = [buf1, buf2] >>arr.sort(Buffer.compare) [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ] >>buf.toJSON() {type: 'Buffer', data: [104, 101, 121, 101, 108]} >> buf = new Buffer('Hello World!'); >> buf2 0 buf.slice(0,3) buf2.toString(); 'Hel'
In this lesson, we cover the Node.js Buffer object in detail. Not only will you learn that the buffer object is a reference to a memory space outside of the V8 engine, but you will learn practical methods to access it, modify it, and convert it to standard Javascript objects that can be used by your code. Examples and discussion are provided for using the toString() method, determining the byte length of the buffer, writing to a buffer, how to avoid truncating data, comparing buffers for equality using both compare() and equals(), and copying buffers using slice().
分类:
Node.js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具