diff --git a/doc/api/buffer.markdown b/doc/api/buffer.markdown index 090a3eef51acbd..93e4baceffd984 100644 --- a/doc/api/buffer.markdown +++ b/doc/api/buffer.markdown @@ -290,6 +290,25 @@ Example: build a single Buffer from a list of three Buffers: // // 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 diff --git a/lib/buffer.js b/lib/buffer.js index 00be048d4a6e0b..a8d9bc1c452d34 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -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;