Why am I getting this error? r1= buf1.compare(buf2); ^ TypeError: Object Rahul has no method 'compare'

Why am I getting this error? r1= buf1.compare(buf2); ^ TypeError: Object Rahul has no method 'compare'

/*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);

'compare' 不是原型函数。 它应该用作:

Buffer.compare(b1,b2)

添加了代码示例:

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

看起来 Buffer.compare 方法是在节点 0.12 中引入的。例如0.10 可以将缓冲区转换为数组或字符串并进行比较。

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

Harder/faster 正确的方法是实际编写比较函数,逐字节检查缓冲区是否相等,returns 正确 -101 作为结果(需要排序)。