Home  >  Article  >  Web Front-end  >  Instructions for using the buffer.toString method in node.js

Instructions for using the buffer.toString method in node.js

PHPz
PHPzOriginal
2016-05-16 16:27:214512browse

This article mainly introduces the instructions for using the buffer.toString method in node.js. This article introduces the method description, syntax, receiving parameters, usage examples and implementation source code of buffer.toString. Friends in need can refer to it.

Method description:

Convert the buffer object into a string with the specified character encoding.

Syntax:

buffer.toString([encoding], [start], [end]);

Receive parameters:

encoding: character encoding after conversion to string, default is 'utf8';

start: the starting position of the buffer conversion, the default is 0;

end: the end position of the buffer conversion, the default is the buffer length.

Example:

var b = new Buffer(50);
 
console.log(b);
 
var c = b.toString('base64',0,10);
 
console.log(c);

Source code:

// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function(encoding, start, end) {
  var loweredCase = false;
  start = start >>> 0;
  end = util.isUndefined(end) ? this.length : end >>> 0;
  if (!encoding) encoding = 'utf8';
  if (start < 0) start = 0;
  if (end > this.length) end = this.length;
  if (end <= start) return &#39;&#39;;
  while (true) {
    switch (encoding) {
      case &#39;hex&#39;:
        return this.hexSlice(start, end);
      case &#39;utf8&#39;:
      case &#39;utf-8&#39;:
        return this.utf8Slice(start, end);
      case &#39;ascii&#39;:
        return this.asciiSlice(start, end);
      case &#39;binary&#39;:
        return this.binarySlice(start, end);
      case &#39;base64&#39;:
        return this.base64Slice(start, end);
      case &#39;ucs2&#39;:
      case &#39;ucs-2&#39;:
      case &#39;utf16le&#39;:
      case &#39;utf-16le&#39;:
        return this.ucs2Slice(start, end);
      default:
        if (loweredCase)
          throw new TypeError(&#39;Unknown encoding: &#39; + encoding);
        encoding = (encoding + &#39;&#39;).toLowerCase();
        loweredCase = true;
    }
  }
};

The above is the entire content of this chapter, more related For tutorials, please visit Node.js Video Tutorial!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn