buffer: add pending deprecation warning · nodejs/node@d2d32ea
@@ -22,18 +22,20 @@
2222'use strict';
23232424const binding = process.binding('buffer');
25+const config = process.binding('config');
2526const { compare: compare_, compareOffset } = binding;
2627const { isAnyArrayBuffer, isUint8Array } = process.binding('util');
2728const bindingObj = {};
2829const internalUtil = require('internal/util');
30+const pendingDeprecation = !!config.pendingDeprecation;
29313032class FastBuffer extends Uint8Array {
3133constructor(arg1, arg2, arg3) {
3234super(arg1, arg2, arg3);
3335}
3436}
35-3637FastBuffer.prototype.constructor = Buffer;
38+3739Buffer.prototype = FastBuffer.prototype;
38403941exports.Buffer = Buffer;
@@ -83,6 +85,28 @@ function alignPool() {
8385}
8486}
858788+var bufferWarn = true;
89+const bufferWarning = 'The Buffer() and new Buffer() constructors are not ' +
90+'recommended for use due to security and usability ' +
91+'concerns. Please use the new Buffer.alloc(), ' +
92+'Buffer.allocUnsafe(), or Buffer.from() construction ' +
93+'methods instead.';
94+95+function showFlaggedDeprecation() {
96+if (bufferWarn) {
97+// This is a *pending* deprecation warning. It is not emitted by
98+// default unless the --pending-deprecation command-line flag is
99+// used or the NODE_PENDING_DEPRECATION=1 envvar is set.
100+process.emitWarning(bufferWarning, 'DeprecationWarning', 'DEP0005');
101+bufferWarn = false;
102+}
103+}
104+105+const doFlaggedDeprecation =
106+pendingDeprecation ?
107+showFlaggedDeprecation :
108+function() {};
109+86110/**
87111 * The Buffer() construtor is deprecated in documentation and should not be
88112 * used moving forward. Rather, developers should use one of the three new
@@ -94,6 +118,7 @@ function alignPool() {
94118 * Deprecation Code: DEP0005
95119 **/
96120function Buffer(arg, encodingOrOffset, length) {
121+doFlaggedDeprecation();
97122// Common case.
98123if (typeof arg === 'number') {
99124if (typeof encodingOrOffset === 'string') {
@@ -106,6 +131,12 @@ function Buffer(arg, encodingOrOffset, length) {
106131return Buffer.from(arg, encodingOrOffset, length);
107132}
108133134+Object.defineProperty(Buffer, Symbol.species, {
135+enumerable: false,
136+configurable: true,
137+get() { return FastBuffer; }
138+});
139+109140/**
110141 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
111142 * if value is a number.