Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions doc/api/buffer.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,25 @@ Example: build a single Buffer from a list of three Buffers:
// <Buffer 00 00 00 00 ...>
// 42

### Class Method: Buffer.encode(str[, encoding])

* `str` {String} string to encode.
* `encoding` {String} encoding to use, Optional.
* Return: Buffer

Encoding a string with more safely.

const str = '100';
const number = 100;
const buf1 = new Buffer(str); // allocate 3 bytes
const buf2 = new Buffer(number); // allocate 100 bytes

const value = ? // when value is come from outside

const buf3 = new Buffer(value); // wtf?

const buf4 = Buffer.encode(value); // allocate bytes safely

### Class Method: Buffer.isBuffer(obj)

* `obj` Object
Expand Down
7 changes: 7 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,13 @@ Buffer.compare = function compare(a, b) {
return binding.compare(a, b);
};

Buffer.encode = function(str, encoding) {
// convert string safely
if (typeof str !== 'string') {
str = '' + str;
}
return new Buffer(str, encoding);
};

Buffer.isEncoding = function(encoding) {
var loweredCase = false;
Expand Down