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);