Nodejs:将string转换为缓冲区

我试图写一个string到套接字(套接字称为“响应”)。 这里是我有sofar的代码(我试图实现一个字节caching代理…):

var http = require('http'); var sys=require('sys'); var localHash={}; http.createServer(function(request, response) { var proxy = http.createClient(80, request.headers['host']) var proxy_request = proxy.request(request.method, request.url, request.headers); proxy_request.addListener('response', function (proxy_response) { proxy_response.addListener('data', function(x) { var responseData=x.toString(); var f=50; var toTransmit=""; var p=0; var N=responseData.length; if(N>f){ p=Math.floor(N/f); var hash=""; var chunk=""; for(var i=0;i<p;i++){ chunk=responseData.substr(f*i,f); hash=DJBHash(chunk); if(localHash[hash]==undefined){ localHash[hash]=chunk; toTransmit=toTransmit+chunk; }else{ sys.puts("***hit"+chunk); toTransmit=toTransmit+chunk;//"***EOH"+hash; } } //remainder: chunk=responseData.substr(f*p); hash=DJBHash(chunk); if(localHash[hash]==undefined){ localHash[hash]=chunk; toTransmit=toTransmit+chunk; }else{ toTransmit=toTransmit+chunk;//"***EOH"+hash; } }else{ toTransmit=responseData; } response.write(new Buffer(toTransmit)); /*error occurs here */ }); proxy_response.addListener('end', function() { response.end(); }); response.writeHead(proxy_response.statusCode, proxy_response.headers); }); request.addListener('data', function(chunk) { sys.puts(chunk); proxy_request.write(chunk, 'binary'); }); request.addListener('end', function() { proxy_request.end(); }); }).listen(8080); function DJBHash(str) { var hash = 5381; for(var i = 0; i < str.length; i++) { hash = (((hash << 5) + hash) + str.charCodeAt(i)) & 0xffffffff; } if(hash<-1){ hash=hash*-1; } return hash; } 

麻烦的是,我一直在Firefox中收到“内容编码错误”。 就好像内容传输不正常。 我已经确保“toTransmit”和console.log(x)和console.log(toTransmit)中的“x”是一样的。

值得注意的是,如果我用response.write(new Buffer(toTransmit)) response.write(x)replaceresponse.write(new Buffer(toTransmit)) ,代理将按照预期工作,但是我需要做一些有效负载分析,然后传递“toTransmit”而不是“x ”。

我也试图response.write(toTransmit) (即没有转换到缓冲区),我不断收到相同的内容编码错误。

我真的被卡住了 我以为我有这个问题通过将string转换为一个缓冲区解决,因为每个线程(但我已经重新打开一个新的线程(http://stackoverflow.com/questions/7090510/nodejs-content-encoding-error)来讨论我遇到的这个新问题。

我应该补充说,如果我通过代理在Opera中打开一个页面,我得到了gobblydeegook–就好像压缩的数据被破坏了一样。

任何见解非常感谢。

提前谢谢了,

不深入你的代码,在我看来,你可能想改变

 var responseData=x.toString(); 

 var responseData=x.toString("binary"); 

最后

 response.write(new Buffer(toTransmit, "binary")); 

这个怎么样?

 var responseData= Buffer.from( x, 'utf8' ) 

from: 将string转换为缓冲区节点

从文档 :

纯Javascript是Unicode友好的,但对二进制数据不好。 处理TCPstream或文件系统时,需要处理八位字节stream。 节点有几个操作,创build和消费八位字节stream的策略。

原始数据存储在Buffer类的实例中。 缓冲区类似于整数数组,但对应于V8堆外部的原始内存分配。 缓冲区不能resize。

所以,不要使用string来处理二进制数据。

更改proxy_request.write(chunk, 'binary');proxy_request.write(chunk);

忽略var responseData=x.toString(); ,这是一个坏主意。

而不是在substr上执行substr ,在缓冲区上使用slice

不要使用string+ ,而是使用buffertools中的“concat”方法。