Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js/ Getting buffer on data.socket

Tags:

node.js

I use node.js, and have the next code:

var server = net.createServer(function(socket) {
socket.on('data', function(d) {
console.log(d);}}

I see that it prints the next:

<Buffer 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0..>

Even if I open a conection in my localhost. What can be the reason? How I change it that it would get the http request?

like image 238
user2450886 Avatar asked Jun 14 '13 11:06

user2450886


1 Answers

According to the docs, you must specify the encoding with the setEncoding() method to receive an string.
If you don't, you'll receive an Buffer with raw data because Node will not know what encoding you want - and Node deals with very low level networking.

For example:

var server = net.createServer(function(socket) {
  socket.setEncoding("utf8");
  socket.on('data', function(d) {
    console.log(d); // will be string
  }
}

If you don't want to, you can always call toString():

var server = net.createServer(function(socket) {
  socket.on('data', function(d) {
    console.log(d.toString());
  }
}
like image 179
gustavohenke Avatar answered Nov 12 '22 10:11

gustavohenke