nodejs: string manipulation

2020-07-16 08:58发布

I have the following node.js code:

   conn.on("data",function(x){
       var responseData=x;
       //sys.puts(responseData);
       sys.puts(responseData.length);

       var f=50;
       var N=responseData.length;
       if(N>f){
         var p=Math.floor(N/f);
         var p_rem=N%f;

         var hash="";
         for(var i=0;i<p;i++){
           hash=DJBHash(responseData.substr(f*i,f));   //this line causes program to exit!
           sys.puts(responseData.substr(f*i,f)+"***"+hash);
         }
       }
       soc.write(x);
    });

But substr doesn't appear to work!

How can I get substrings of a string in node.js?

Many thanks in advance,

1条回答
走好不送
2楼-- · 2020-07-16 09:13

The variable data is of type Buffer, you would have to create a string with the method toString and then, you will be able to do the substr. Something like that will work :

responseData.toString().substr(1)

For more info consult this link :

http://nodejs.org/docs/v0.4.10/api/buffers.html#buffer.toString

查看更多
登录 后发表回答