From f2fe5583c434e9864a1171209908c3a24b9d54bb Mon Sep 17 00:00:00 2001 From: Nikolai Vavilov Date: Thu, 18 Aug 2016 22:03:56 +0300 Subject: [PATCH] buffer: runtime deprecation of calling Buffer without new MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/8169 Reviewed-By: Anna Henningsen Reviewed-By: Stephen Belanger Reviewed-By: Сковорода Никита Андреевич Reviewed-By: James M Snell --- lib/buffer.js | 10 ++++++++++ test/parallel/test-buffer-deprecated.js | 17 +++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 test/parallel/test-buffer-deprecated.js diff --git a/lib/buffer.js b/lib/buffer.js index c5e5a4e58fe296..e41e3662662609 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -64,7 +64,17 @@ function alignPool() { * much breakage at this time. It's not likely that the Buffer constructors * would ever actually be removed. **/ +var newBufferWarned = false; function Buffer(arg, encodingOrOffset, length) { + if (!new.target && !newBufferWarned) { + newBufferWarned = true; + process.emitWarning( + 'Using Buffer without `new` will soon stop working. ' + + 'Use `new Buffer()`, or preferably ' + + '`Buffer.from()`, `Buffer.allocUnsafe()` or `Buffer.alloc()` instead.', + 'DeprecationWarning' + ); + } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { diff --git a/test/parallel/test-buffer-deprecated.js b/test/parallel/test-buffer-deprecated.js new file mode 100644 index 00000000000000..21a9ce9ed6dcd6 --- /dev/null +++ b/test/parallel/test-buffer-deprecated.js @@ -0,0 +1,17 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); + +const expected = + 'Using Buffer without `new` will soon stop working. ' + + 'Use `new Buffer()`, or preferably ' + + '`Buffer.from()`, `Buffer.allocUnsafe()` or `Buffer.alloc()` instead.'; + +process.on('warning', common.mustCall((warning) => { + assert.strictEqual(warning.name, 'DeprecationWarning'); + assert.strictEqual(warning.message, expected, + `unexpected error message: "${warning.message}"`); +}, 1)); + +Buffer(1); +Buffer(1);