如何将utf-16缓冲区与字符串进行比较



我有一个缓冲区,看起来像这样:

<Buffer 50 00 6f 00 77 00 65 00 72 00 50 00 6f 00 69 00 6e 00 74 00 20 00 44 00 6f 00 63 00 75 00 6d 00 65 00 6e 00 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ...>

当用utf-16le读取此缓冲区或用.toString()打印此缓冲区时,这就是"PowerPoint文档"

但是,如果我这样做:

var stream = fs.createReadStream('test.ppt',{start:1152,end:1215,encoding:'utf16le'})
    stream
    .on('data',function(chunk){
        console.log(chunk.toString().trim());
        console.log(chunk.toString().trim().length);
        if(chunk.toString().trim() === "PowerPoint Document"){
            console.log('yay');
        }else{
            console.log('boo');
        }

此打印:

PowerPoint Document  
32
boo

我该如何比较这些?

您的字符串以null结尾。由于字节1152-1215看起来像

0480h: 50 00 6F 00 77 00 65 00 72 00 50 00 6F 00 69 00  P.o.w.e.r.P.o.i. 
0490h: 6E 00 74 00 20 00 44 00 6F 00 63 00 75 00 6D 00  n.t. .D.o.c.u.m. 
04A0h: 65 00 6E 00 74 00 00 00 00 00 00 00 00 00 00 00  e.n.t........... 
04B0h: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................ 

最后的所有空字节都将被转换为u0000,所以你实际上是在比较:

'PowerPoint Documentu0000u0000...' === 'PowerPoint Document'

这显然是错误的。

结束于字节1189。

BTW:流data事件不能保证用您请求的所有数据触发。它可能只对部分数据进行多次激发(这就是它被称为chunk的原因)。您必须缓冲所有data事件,直到得到一个end事件,然后进行比较。

最新更新