6

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?

1
  • If you want the HTTP request, you should use http.createServer. Commented Jun 14, 2013 at 12:23

1 Answer 1

10

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());
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or use d.toString() as an alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.