为什么我得到这个错误? r1 = buf1.compare(buf2); ^ TypeError:对象Rahul没有方法'比较'

/*This a demo program to campare buffers to each other. The expected output should be some numbers so that we came to know that these are equal or not. taking three buffer variables and storing some data into it. */ var buf1 = new Buffer('Rahul'); Buffer contains Rahul var buf2 = new Buffer('Kumar'); Buffer contains Kumar var buf3 = new Buffer('Rahul'); Buffer contains Rahul //now comparing these buffers to each other r1= buf1.compare(buf2); r2= buf1.compare(buf3); r3= buf2.compare(buf3); //Printing them to console console.log(r1+ " " + r2 + " " + r3); 

       

网上收集的解决方案 "为什么我得到这个错误? r1 = buf1.compare(buf2); ^ TypeError:对象Rahul没有方法'比较'"

“比较”不是原型function。 它应该用作:

 Buffer.compare(b1,b2) 

增加了代码示例:

 var b1=new Buffer("a"); var b2=new Buffer("b"); var r=Buffer.compare(b1,b2); console.log(r); 

看起来像节点0.12中引入了Buffer.compare方法。 例如,0.10可以将缓冲区转换为数组或string并进行比较。

简单(不是很有效)的方法来检查Buffer相等就是将缓冲区转换为带有JSON.stringify(b1)string并进行string比较。

更难/更快,更正确的方法是实际编写比较函数,它逐字节地检查缓冲区是否相等,并返回正确的-11作为结果(需要进行sorting)。