From 85ab4a5f1281c4e1dd06450ac7bd3250326267fa Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 25 Jan 2016 15:00:06 -0800 Subject: [PATCH] buffer: add .from(), .alloc() and .allocUnsafe() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Several changes: * Soft-Deprecate Buffer() constructors * Add `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()` * Add `--zero-fill-buffers` command line option * Add byteOffset and length to `new Buffer(arrayBuffer)` constructor * buffer.fill('') previously had no effect, now zero-fills * Update the docs PR-URL: https://github.com/nodejs/node/pull/4682 Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Stephen Belanger --- benchmark/buffers/buffer-base64-decode.js | 2 +- benchmark/buffers/buffer-base64-encode.js | 2 +- benchmark/buffers/buffer-bytelength.js | 2 +- benchmark/buffers/buffer-compare.js | 8 +- benchmark/buffers/buffer-creation.js | 61 +- benchmark/buffers/buffer-indexof.js | 4 +- benchmark/buffers/buffer-slice.js | 2 +- benchmark/buffers/buffer-tostring.js | 2 +- benchmark/buffers/buffer_zero.js | 4 +- benchmark/crypto/aes-gcm-throughput.js | 4 +- benchmark/crypto/cipher-stream.js | 3 +- benchmark/crypto/hash-stream-creation.js | 5 +- benchmark/crypto/hash-stream-throughput.js | 3 +- .../crypto/rsa-encrypt-decrypt-throughput.js | 3 +- .../crypto/rsa-sign-verify-throughput.js | 3 +- benchmark/dgram/array-vs-concat.js | 2 +- benchmark/dgram/multi-buffer.js | 2 +- benchmark/dgram/offset-length.js | 2 +- benchmark/dgram/single-buffer.js | 2 +- benchmark/fs-write-stream-throughput.js | 3 +- benchmark/fs/read-stream-throughput.js | 2 +- benchmark/fs/readfile.js | 3 +- benchmark/fs/write-stream-throughput.js | 3 +- benchmark/http/bench-parser.js | 2 +- benchmark/http/chunked.js | 3 +- benchmark/http/client-request-body.js | 3 +- benchmark/http/end-vs-write-end.js | 3 +- benchmark/http_simple.js | 2 +- benchmark/http_simple_auto.js | 2 +- benchmark/net/net-c2s-cork.js | 3 +- benchmark/net/net-c2s.js | 3 +- benchmark/net/net-pipe.js | 3 +- benchmark/net/net-s2c.js | 3 +- benchmark/net/tcp-raw-c2s.js | 3 +- benchmark/net/tcp-raw-pipe.js | 3 +- benchmark/net/tcp-raw-s2c.js | 3 +- benchmark/string_decoder/string-decoder.js | 10 +- benchmark/tls/throughput.js | 4 +- doc/api/buffer.markdown | 533 ++++-- doc/node.1 | 3 + lib/_debugger.js | 2 +- lib/_http_client.js | 2 +- lib/_http_outgoing.js | 2 +- lib/_stream_readable.js | 4 +- lib/_stream_writable.js | 2 +- lib/_tls_legacy.js | 2 +- lib/_tls_wrap.js | 4 +- lib/assert.js | 2 +- lib/buffer.js | 138 +- lib/child_process.js | 2 +- lib/crypto.js | 2 +- lib/dgram.js | 6 +- lib/fs.js | 22 +- lib/internal/v8_prof_polyfill.js | 2 +- lib/net.js | 2 +- lib/querystring.js | 2 +- lib/string_decoder.js | 2 +- lib/tls.js | 4 +- lib/zlib.js | 10 +- src/node.cc | 8 +- src/node_buffer.cc | 27 +- src/node_buffer.h | 3 + test/disabled/test-debug-brk-file.js | 2 +- test/disabled/test-dgram-send-error.js | 3 +- test/disabled/test-fs-largefile.js | 5 +- test/disabled/test-sendfd.js | 2 +- test/fixtures/GH-892-request.js | 2 +- test/fixtures/print-chars-from-buffer.js | 2 +- .../test-dgram-broadcast-multi-process.js | 8 +- .../test-dgram-multicast-multi-process.js | 8 +- .../test-dgram-send-cb-quelches-error.js | 2 +- .../test-async-wrap-check-providers.js | 2 +- test/parallel/test-buffer-alloc.js | 1442 +++++++++++++++++ test/parallel/test-buffer-arraybuffer.js | 62 +- test/parallel/test-buffer-ascii.js | 4 +- test/parallel/test-buffer-bytelength.js | 4 +- test/parallel/test-buffer-concat.js | 8 +- test/parallel/test-buffer-fakes.js | 6 +- test/parallel/test-buffer-fill.js | 14 +- test/parallel/test-buffer-includes.js | 72 +- test/parallel/test-buffer-indexof.js | 82 +- test/parallel/test-buffer-inspect.js | 8 +- test/parallel/test-buffer-iterator.js | 2 +- test/parallel/test-buffer-safe-unsafe.js | 14 + test/parallel/test-buffer-slow.js | 11 +- test/parallel/test-buffer-zero-fill-cli.js | 32 + test/parallel/test-buffer-zero-fill-reset.js | 2 +- test/parallel/test-buffer.js | 89 +- .../parallel/test-child-process-fork-dgram.js | 2 +- .../test-child-process-spawnsync-input.js | 8 +- .../test-child-process-spawnsync-maxbuf.js | 2 +- .../test-child-process-stdio-big-write-end.js | 6 +- test/parallel/test-cluster-dgram-1.js | 2 +- test/parallel/test-cluster-dgram-2.js | 2 +- test/parallel/test-crypto-authenticated.js | 26 +- test/parallel/test-crypto-binary-default.js | 74 +- test/parallel/test-crypto-cipher-decipher.js | 4 +- .../test-crypto-cipheriv-decipheriv.js | 8 +- test/parallel/test-crypto-dh-odd-key.js | 3 +- test/parallel/test-crypto-dh.js | 4 +- test/parallel/test-crypto-from-binary.js | 2 +- test/parallel/test-crypto-hash.js | 4 +- test/parallel/test-crypto-hmac.js | 60 +- test/parallel/test-crypto-padding-aes256.js | 4 +- test/parallel/test-crypto-rsa-dsa.js | 14 +- test/parallel/test-crypto-stream.js | 6 +- test/parallel/test-dgram-bytes-length.js | 2 +- .../test-dgram-close-is-not-callback.js | 3 +- test/parallel/test-dgram-close.js | 3 +- test/parallel/test-dgram-empty-packet.js | 7 +- .../test-dgram-exclusive-implicit-bind.js | 2 +- test/parallel/test-dgram-implicit-bind.js | 4 +- test/parallel/test-dgram-msgsize.js | 2 +- test/parallel/test-dgram-oob-buffer.js | 2 +- .../parallel/test-dgram-send-bad-arguments.js | 2 +- .../test-dgram-send-callback-buffer-length.js | 2 +- .../test-dgram-send-callback-buffer.js | 2 +- .../test-dgram-send-callback-multi-buffer.js | 8 +- test/parallel/test-dgram-send-default-host.js | 9 +- test/parallel/test-dgram-send-empty-buffer.js | 2 +- test/parallel/test-file-write-stream3.js | 4 +- test/parallel/test-fs-append-file-sync.js | 2 +- test/parallel/test-fs-append-file.js | 2 +- .../test-fs-read-buffer-tostring-fail.js | 2 +- .../test-fs-read-buffer-zero-length.js | 8 +- test/parallel/test-fs-read-buffer.js | 8 +- test/parallel/test-fs-read-stream-encoding.js | 2 +- .../test-fs-readfile-tostring-fail.js | 2 +- test/parallel/test-fs-readfile-unlink.js | 3 +- test/parallel/test-fs-sir-writes-alot.js | 3 +- test/parallel/test-fs-truncate.js | 3 +- test/parallel/test-fs-write-buffer.js | 3 +- test/parallel/test-fs-write-file-buffer.js | 2 +- test/parallel/test-fs-write-file.js | 2 +- test/parallel/test-fs-write-no-fd.js | 2 +- .../parallel/test-fs-write-stream-encoding.js | 2 +- test/parallel/test-fs-write-stream-err.js | 4 +- test/parallel/test-fs-write-sync.js | 2 +- test/parallel/test-http-buffer-sanity.js | 2 +- test/parallel/test-http-byteswritten.js | 3 +- test/parallel/test-http-client-upload-buf.js | 2 +- test/parallel/test-http-outgoing-finish.js | 3 +- test/parallel/test-http-parser-bad-ref.js | 6 +- test/parallel/test-http-parser.js | 30 +- test/parallel/test-http-pipeline-flood.js | 2 +- test/parallel/test-http-pipeline-regr-3332.js | 3 +- test/parallel/test-http-pipeline-regr-3508.js | 3 +- test/parallel/test-http-regr-gh-2821.js | 3 +- ...test-http-res-write-end-dont-take-array.js | 4 +- test/parallel/test-http-write-callbacks.js | 4 +- test/parallel/test-https-drain.js | 2 +- .../parallel/test-https-resume-after-renew.js | 9 +- test/parallel/test-https-truncate.js | 2 +- test/parallel/test-net-connect-buffer.js | 4 +- test/parallel/test-net-error-twice.js | 4 +- test/parallel/test-net-stream.js | 3 +- test/parallel/test-net-write-slow.js | 3 +- test/parallel/test-readline-interface.js | 4 +- test/parallel/test-regress-GH-io-1811.js | 2 +- test/parallel/test-stream-big-packet.js | 3 +- .../test-stream-pipe-cleanup-pause.js | 2 +- test/parallel/test-stream-readable-event.js | 6 +- .../test-stream-readable-flow-recursion.js | 2 +- ...tream-transform-constructor-set-methods.js | 2 +- .../test-stream-transform-split-objectmode.js | 4 +- .../test-stream-unshift-empty-chunk.js | 8 +- .../parallel/test-stream-unshift-read-race.js | 8 +- ...stream-writable-constructor-set-methods.js | 6 +- test/parallel/test-stream-writev.js | 2 +- ...est-stream2-base64-single-char-read-end.js | 2 +- test/parallel/test-stream2-compatibility.js | 5 +- test/parallel/test-stream2-finish-pipe.js | 2 +- .../parallel/test-stream2-large-read-stall.js | 2 +- .../test-stream2-pipe-error-handling.js | 4 +- test/parallel/test-stream2-read-sync-stack.js | 2 +- ...st-stream2-readable-empty-buffer-no-eof.js | 16 +- .../test-stream2-readable-from-list.js | 8 +- .../test-stream2-readable-legacy-drain.js | 2 +- .../test-stream2-readable-non-empty-end.js | 2 +- test/parallel/test-stream2-readable-wrap.js | 4 +- test/parallel/test-stream2-set-encoding.js | 3 +- test/parallel/test-stream2-transform.js | 99 +- test/parallel/test-stream2-unpipe-leak.js | 2 +- test/parallel/test-stream2-writable.js | 24 +- test/parallel/test-stream3-pause-then-read.js | 3 +- test/parallel/test-string-decoder-end.js | 4 +- test/parallel/test-string-decoder.js | 15 +- .../test-stringbytes-external-at-max.js | 4 +- test/parallel/test-stringbytes-external.js | 16 +- test/parallel/test-tls-alert-handling.js | 2 +- test/parallel/test-tls-cert-regression.js | 2 +- test/parallel/test-tls-client-destroy-soon.js | 4 +- .../parallel/test-tls-delayed-attach-error.js | 3 +- test/parallel/test-tls-fast-writing.js | 3 +- .../parallel/test-tls-hello-parser-failure.js | 3 +- test/parallel/test-tls-inception.js | 2 +- test/parallel/test-tls-max-send-fragment.js | 2 +- test/parallel/test-tls-ocsp-callback.js | 2 +- test/parallel/test-tls-pause.js | 2 +- test/parallel/test-tty-wrap.js | 4 +- test/parallel/test-util.js | 2 +- test/parallel/test-zlib-dictionary-fail.js | 6 +- test/parallel/test-zlib-dictionary.js | 2 +- test/parallel/test-zlib-flush-drain.js | 2 +- test/parallel/test-zlib-flush.js | 6 +- test/parallel/test-zlib-from-string.js | 4 +- test/parallel/test-zlib-params.js | 2 +- test/parallel/test-zlib-random-byte-pipes.js | 2 +- test/parallel/test-zlib-zero-byte.js | 2 +- test/parallel/test-zlib.js | 2 +- test/pummel/test-https-no-reader.js | 2 +- test/pummel/test-regress-GH-814.js | 4 +- test/pummel/test-regress-GH-814_2.js | 4 +- test/pummel/test-stream-pipe-multi.js | 2 +- test/pummel/test-stream2-basic.js | 7 +- test/pummel/test-tls-server-large-request.js | 2 +- test/sequential/test-buffer-bad-overload.js | 6 +- .../sequential/test-child-process-execsync.js | 2 +- test/sequential/test-net-GH-5504.js | 4 +- test/sequential/test-pipe.js | 3 +- test/sequential/test-regress-GH-1697.js | 4 +- ...ingbytes-external-exceed-max-by-1-ascii.js | 4 +- ...ngbytes-external-exceed-max-by-1-base64.js | 4 +- ...ngbytes-external-exceed-max-by-1-binary.js | 4 +- ...tringbytes-external-exceed-max-by-1-hex.js | 4 +- ...ringbytes-external-exceed-max-by-1-utf8.js | 4 +- ...st-stringbytes-external-exceed-max-by-2.js | 4 +- .../test-stringbytes-external-exceed-max.js | 4 +- test/sequential/test-zerolengthbufferbug.js | 2 +- 229 files changed, 2824 insertions(+), 853 deletions(-) create mode 100644 test/parallel/test-buffer-alloc.js create mode 100644 test/parallel/test-buffer-safe-unsafe.js create mode 100644 test/parallel/test-buffer-zero-fill-cli.js diff --git a/benchmark/buffers/buffer-base64-decode.js b/benchmark/buffers/buffer-base64-decode.js index 36094f632d4eec..3497bfd05fd2a2 100644 --- a/benchmark/buffers/buffer-base64-decode.js +++ b/benchmark/buffers/buffer-base64-decode.js @@ -8,7 +8,7 @@ function main(conf) { const s = 'abcd'.repeat(8 << 20); s.match(/./); // Flatten string. assert.equal(s.length % 4, 0); - const b = Buffer(s.length / 4 * 3); + const b = Buffer.allocUnsafe(s.length / 4 * 3); b.write(s, 0, s.length, 'base64'); bench.start(); for (var i = 0; i < 32; i += 1) b.base64Write(s, 0, s.length); diff --git a/benchmark/buffers/buffer-base64-encode.js b/benchmark/buffers/buffer-base64-encode.js index 8e2eec3cf5bb37..930dc82b6b9ab7 100644 --- a/benchmark/buffers/buffer-base64-encode.js +++ b/benchmark/buffers/buffer-base64-encode.js @@ -5,7 +5,7 @@ var bench = common.createBenchmark(main, {}); function main(conf) { var N = 64 * 1024 * 1024; - var b = Buffer(N); + var b = Buffer.allocUnsafe(N); var s = ''; var i; for (i = 0; i < 256; ++i) s += String.fromCharCode(i); diff --git a/benchmark/buffers/buffer-bytelength.js b/benchmark/buffers/buffer-bytelength.js index 50f420f412d30b..273115b3def420 100644 --- a/benchmark/buffers/buffer-bytelength.js +++ b/benchmark/buffers/buffer-bytelength.js @@ -28,7 +28,7 @@ function main(conf) { strings.push(data); } else if (encoding === 'base64') { // Base64 strings will be much longer than their UTF8 counterparts - strings.push(new Buffer(data, 'utf8').toString('base64')); + strings.push(Buffer.from(data, 'utf8').toString('base64')); } } diff --git a/benchmark/buffers/buffer-compare.js b/benchmark/buffers/buffer-compare.js index c83bb67fa24ad8..84faf84e34aac7 100644 --- a/benchmark/buffers/buffer-compare.js +++ b/benchmark/buffers/buffer-compare.js @@ -7,10 +7,10 @@ var bench = common.createBenchmark(main, { }); function main(conf) { - var iter = (conf.millions >>> 0) * 1e6; - var size = (conf.size >>> 0); - var b0 = new Buffer(size).fill('a'); - var b1 = new Buffer(size).fill('a'); + const iter = (conf.millions >>> 0) * 1e6; + const size = (conf.size >>> 0); + const b0 = Buffer.alloc(size, 'a'); + const b1 = Buffer.alloc(size, 'a'); b1[size - 1] = 'b'.charCodeAt(0); diff --git a/benchmark/buffers/buffer-creation.js b/benchmark/buffers/buffer-creation.js index dfb68467cc54b9..e0e64d6934dcf3 100644 --- a/benchmark/buffers/buffer-creation.js +++ b/benchmark/buffers/buffer-creation.js @@ -1,20 +1,59 @@ 'use strict'; const SlowBuffer = require('buffer').SlowBuffer; -var common = require('../common.js'); -var bench = common.createBenchmark(main, { - type: ['fast', 'slow'], - len: [10, 1024], +const common = require('../common.js'); +const assert = require('assert'); +const bench = common.createBenchmark(main, { + type: [ + 'fast-alloc', + 'fast-alloc-fill', + 'fast-allocUnsafe', + 'slow', + 'buffer()'], + len: [10, 1024, 2048, 4096, 8192], n: [1024] }); function main(conf) { - var len = +conf.len; - var n = +conf.n; - var clazz = conf.type === 'fast' ? Buffer : SlowBuffer; - bench.start(); - for (var i = 0; i < n * 1024; i++) { - new clazz(len); + const len = +conf.len; + const n = +conf.n; + switch (conf.type) { + case 'fast-alloc': + bench.start(); + for (let i = 0; i < n * 1024; i++) { + Buffer.alloc(len); + } + bench.end(n); + break; + case 'fast-alloc-fill': + bench.start(); + for (let i = 0; i < n * 1024; i++) { + Buffer.alloc(len, 0); + } + bench.end(n); + break; + case 'fast-allocUnsafe': + bench.start(); + for (let i = 0; i < n * 1024; i++) { + Buffer.allocUnsafe(len); + } + bench.end(n); + break; + case 'slow': + bench.start(); + for (let i = 0; i < n * 1024; i++) { + SlowBuffer(len); + } + bench.end(n); + break; + case 'buffer()': + bench.start(); + for (let i = 0; i < n * 1024; i++) { + Buffer(len); + } + bench.end(n); + break; + default: + assert.fail(null, null, 'Should not get here'); } - bench.end(n); } diff --git a/benchmark/buffers/buffer-indexof.js b/benchmark/buffers/buffer-indexof.js index 6f10033020bc74..380f40b23d8ab6 100644 --- a/benchmark/buffers/buffer-indexof.js +++ b/benchmark/buffers/buffer-indexof.js @@ -27,11 +27,11 @@ function main(conf) { } if (encoding === 'ucs2') { - aliceBuffer = new Buffer(aliceBuffer.toString(), encoding); + aliceBuffer = Buffer.from(aliceBuffer.toString(), encoding); } if (conf.type === 'buffer') { - search = new Buffer(new Buffer(search).toString(), encoding); + search = Buffer.from(Buffer.from(search).toString(), encoding); } bench.start(); diff --git a/benchmark/buffers/buffer-slice.js b/benchmark/buffers/buffer-slice.js index 70cf3a705c0d8b..13dbf6a59b7c76 100644 --- a/benchmark/buffers/buffer-slice.js +++ b/benchmark/buffers/buffer-slice.js @@ -7,7 +7,7 @@ var bench = common.createBenchmark(main, { n: [1024] }); -var buf = new Buffer(1024); +var buf = Buffer.allocUnsafe(1024); var slowBuf = new SlowBuffer(1024); function main(conf) { diff --git a/benchmark/buffers/buffer-tostring.js b/benchmark/buffers/buffer-tostring.js index 937a84b267ed19..99ae0ec077957e 100644 --- a/benchmark/buffers/buffer-tostring.js +++ b/benchmark/buffers/buffer-tostring.js @@ -12,7 +12,7 @@ function main(conf) { const arg = conf.arg === 'true'; const len = conf.len | 0; const n = conf.n | 0; - const buf = Buffer(len).fill(42); + const buf = Buffer.alloc(len, 42); var i; bench.start(); diff --git a/benchmark/buffers/buffer_zero.js b/benchmark/buffers/buffer_zero.js index 461378758b5951..4a63695657be1f 100644 --- a/benchmark/buffers/buffer_zero.js +++ b/benchmark/buffers/buffer_zero.js @@ -6,13 +6,13 @@ const bench = common.createBenchmark(main, { n: [1024] }); -const zero = new Buffer(0); +const zero = Buffer.alloc(0); function main(conf) { var n = +conf.n; bench.start(); for (let i = 0; i < n * 1024; i++) { - new Buffer(zero); + Buffer.from(zero); } bench.end(n); } diff --git a/benchmark/crypto/aes-gcm-throughput.js b/benchmark/crypto/aes-gcm-throughput.js index fc379b21b748bf..0cb32689510dd3 100644 --- a/benchmark/crypto/aes-gcm-throughput.js +++ b/benchmark/crypto/aes-gcm-throughput.js @@ -9,10 +9,10 @@ var bench = common.createBenchmark(main, { }); function main(conf) { - var message = (new Buffer(conf.len)).fill('b'); + var message = Buffer.alloc(conf.len, 'b'); var key = crypto.randomBytes(keylen[conf.cipher]); var iv = crypto.randomBytes(12); - var associate_data = (new Buffer(16)).fill('z'); + var associate_data = Buffer.alloc(16, 'z'); bench.start(); AEAD_Bench(conf.cipher, message, associate_data, key, iv, conf.n, conf.len); } diff --git a/benchmark/crypto/cipher-stream.js b/benchmark/crypto/cipher-stream.js index 5da6f2481ecbc3..b8e1622bf9f8d0 100644 --- a/benchmark/crypto/cipher-stream.js +++ b/benchmark/crypto/cipher-stream.js @@ -48,8 +48,7 @@ function main(conf) { encoding = 'utf8'; break; case 'buf': - message = new Buffer(conf.len); - message.fill('b'); + message = Buffer.alloc(conf.len, 'b'); break; default: throw new Error('unknown message type: ' + conf.type); diff --git a/benchmark/crypto/hash-stream-creation.js b/benchmark/crypto/hash-stream-creation.js index 4bcd37f00aaae8..e7fcde3aa604f3 100644 --- a/benchmark/crypto/hash-stream-creation.js +++ b/benchmark/crypto/hash-stream-creation.js @@ -33,8 +33,7 @@ function main(conf) { encoding = 'utf8'; break; case 'buf': - message = new Buffer(conf.len); - message.fill('b'); + message = Buffer.alloc(conf.len, 'b'); break; default: throw new Error('unknown message type: ' + conf.type); @@ -58,7 +57,7 @@ function legacyWrite(algo, message, encoding, writes, len, outEnc) { // include buffer creation costs for older versions if (outEnc === 'buffer' && typeof res === 'string') - res = new Buffer(res, 'binary'); + res = Buffer.from(res, 'binary'); } bench.end(gbits); diff --git a/benchmark/crypto/hash-stream-throughput.js b/benchmark/crypto/hash-stream-throughput.js index 050bbeb1ae54d3..732c2b89c74fc1 100644 --- a/benchmark/crypto/hash-stream-throughput.js +++ b/benchmark/crypto/hash-stream-throughput.js @@ -32,8 +32,7 @@ function main(conf) { encoding = 'utf8'; break; case 'buf': - message = new Buffer(conf.len); - message.fill('b'); + message = Buffer.alloc(conf.len, 'b'); break; default: throw new Error('unknown message type: ' + conf.type); diff --git a/benchmark/crypto/rsa-encrypt-decrypt-throughput.js b/benchmark/crypto/rsa-encrypt-decrypt-throughput.js index cf0579134cfb62..4d98f9e2d5d859 100644 --- a/benchmark/crypto/rsa-encrypt-decrypt-throughput.js +++ b/benchmark/crypto/rsa-encrypt-decrypt-throughput.js @@ -23,8 +23,7 @@ var bench = common.createBenchmark(main, { }); function main(conf) { - var message = (new Buffer(conf.len)).fill('b'); - + var message = Buffer.alloc(conf.len, 'b'); bench.start(); StreamWrite(conf.algo, conf.keylen, message, conf.n, conf.len); } diff --git a/benchmark/crypto/rsa-sign-verify-throughput.js b/benchmark/crypto/rsa-sign-verify-throughput.js index 779cc8bca1c6a8..c5db94687a1aac 100644 --- a/benchmark/crypto/rsa-sign-verify-throughput.js +++ b/benchmark/crypto/rsa-sign-verify-throughput.js @@ -24,8 +24,7 @@ var bench = common.createBenchmark(main, { }); function main(conf) { - var message = (new Buffer(conf.len)).fill('b'); - + var message = Buffer.alloc(conf.len, 'b'); bench.start(); StreamWrite(conf.algo, conf.keylen, message, conf.writes, conf.len); } diff --git a/benchmark/dgram/array-vs-concat.js b/benchmark/dgram/array-vs-concat.js index ee74ff66b92b4e..e47229811e8471 100644 --- a/benchmark/dgram/array-vs-concat.js +++ b/benchmark/dgram/array-vs-concat.js @@ -31,7 +31,7 @@ function main(conf) { chunk = []; for (var i = 0; i < chunks; i++) { - chunk.push(new Buffer(Math.round(len / chunks))); + chunk.push(Buffer.allocUnsafe(Math.round(len / chunks))); } server(); diff --git a/benchmark/dgram/multi-buffer.js b/benchmark/dgram/multi-buffer.js index 22c30594196711..e7292feb1f958c 100644 --- a/benchmark/dgram/multi-buffer.js +++ b/benchmark/dgram/multi-buffer.js @@ -31,7 +31,7 @@ function main(conf) { chunk = []; for (var i = 0; i < chunks; i++) { - chunk.push(new Buffer(Math.round(len / chunks))); + chunk.push(Buffer.allocUnsafe(Math.round(len / chunks))); } server(); diff --git a/benchmark/dgram/offset-length.js b/benchmark/dgram/offset-length.js index c11c465f5cf82b..15d9a3d0ee9949 100644 --- a/benchmark/dgram/offset-length.js +++ b/benchmark/dgram/offset-length.js @@ -25,7 +25,7 @@ function main(conf) { len = +conf.len; num = +conf.num; type = conf.type; - chunk = new Buffer(len); + chunk = Buffer.allocUnsafe(len); server(); } diff --git a/benchmark/dgram/single-buffer.js b/benchmark/dgram/single-buffer.js index 765311a72f3903..2676e0e74cfd8b 100644 --- a/benchmark/dgram/single-buffer.js +++ b/benchmark/dgram/single-buffer.js @@ -25,7 +25,7 @@ function main(conf) { len = +conf.len; num = +conf.num; type = conf.type; - chunk = new Buffer(len); + chunk = Buffer.allocUnsafe(len); server(); } diff --git a/benchmark/fs-write-stream-throughput.js b/benchmark/fs-write-stream-throughput.js index 4c767cf666e579..f1c8d3cc1a6d16 100644 --- a/benchmark/fs-write-stream-throughput.js +++ b/benchmark/fs-write-stream-throughput.js @@ -45,8 +45,7 @@ function runTest(dur, size, type) { chunk = new Array(size + 1).join('a'); break; case 'buffer': - chunk = new Buffer(size); - chunk.fill('a'); + chunk = Buffer.alloc(size, 'a'); break; } diff --git a/benchmark/fs/read-stream-throughput.js b/benchmark/fs/read-stream-throughput.js index c305485cd5f8dc..bc55e44c1a18d7 100644 --- a/benchmark/fs/read-stream-throughput.js +++ b/benchmark/fs/read-stream-throughput.js @@ -60,7 +60,7 @@ function runTest() { } function makeFile() { - var buf = new Buffer(filesize / 1024); + var buf = Buffer.allocUnsafe(filesize / 1024); if (encoding === 'utf8') { // ü for (var i = 0; i < buf.length; i++) { diff --git a/benchmark/fs/readfile.js b/benchmark/fs/readfile.js index 0f39f64f57c418..cdb36d065f1c8f 100644 --- a/benchmark/fs/readfile.js +++ b/benchmark/fs/readfile.js @@ -17,8 +17,7 @@ var bench = common.createBenchmark(main, { function main(conf) { var len = +conf.len; try { fs.unlinkSync(filename); } catch (e) {} - var data = new Buffer(len); - data.fill('x'); + var data = Buffer.alloc(len, 'x'); fs.writeFileSync(filename, data); data = null; diff --git a/benchmark/fs/write-stream-throughput.js b/benchmark/fs/write-stream-throughput.js index 4f41d2b4bb4af3..812dc369d7b5b3 100644 --- a/benchmark/fs/write-stream-throughput.js +++ b/benchmark/fs/write-stream-throughput.js @@ -21,8 +21,7 @@ function main(conf) { var chunk; switch (type) { case 'buf': - chunk = new Buffer(size); - chunk.fill('b'); + chunk = Buffer.alloc(size, 'b'); break; case 'asc': chunk = new Array(size + 1).join('a'); diff --git a/benchmark/http/bench-parser.js b/benchmark/http/bench-parser.js index 989d9a994fa04e..0a78f3ffcf2074 100644 --- a/benchmark/http/bench-parser.js +++ b/benchmark/http/bench-parser.js @@ -25,7 +25,7 @@ function main(conf) { } header += CRLF; - processHeader(new Buffer(header), n); + processHeader(Buffer.from(header), n); } diff --git a/benchmark/http/chunked.js b/benchmark/http/chunked.js index 642f2962cdce78..a61978c732233a 100644 --- a/benchmark/http/chunked.js +++ b/benchmark/http/chunked.js @@ -18,8 +18,7 @@ var bench = common.createBenchmark(main, { function main(conf) { const http = require('http'); - var chunk = new Buffer(conf.size); - chunk.fill('8'); + var chunk = Buffer.alloc(conf.size, '8'); var args = ['-d', '10s', '-t', 8, '-c', conf.c]; diff --git a/benchmark/http/client-request-body.js b/benchmark/http/client-request-body.js index befa3811ddd1c3..8d7fae44c1ebf6 100644 --- a/benchmark/http/client-request-body.js +++ b/benchmark/http/client-request-body.js @@ -19,8 +19,7 @@ function main(conf) { var chunk; switch (conf.type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': encoding = 'utf8'; diff --git a/benchmark/http/end-vs-write-end.js b/benchmark/http/end-vs-write-end.js index 4e12e543f0bd92..0cdc88111de146 100644 --- a/benchmark/http/end-vs-write-end.js +++ b/benchmark/http/end-vs-write-end.js @@ -23,8 +23,7 @@ function main(conf) { var len = conf.kb * 1024; switch (conf.type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': chunk = new Array(len / 2 + 1).join('ü'); diff --git a/benchmark/http_simple.js b/benchmark/http_simple.js index 0f36d3b6ce3ebd..699f3b7c0b41cc 100644 --- a/benchmark/http_simple.js +++ b/benchmark/http_simple.js @@ -51,7 +51,7 @@ var server = module.exports = http.createServer(function(req, res) { if (n <= 0) throw new Error('buffer called with n <= 0'); if (storedBuffer[n] === undefined) { - storedBuffer[n] = new Buffer(n); + storedBuffer[n] = Buffer.allocUnsafe(n); for (i = 0; i < n; i++) { storedBuffer[n][i] = 'C'.charCodeAt(0); } diff --git a/benchmark/http_simple_auto.js b/benchmark/http_simple_auto.js index a2271ce1e06a1d..7d209d8a113707 100644 --- a/benchmark/http_simple_auto.js +++ b/benchmark/http_simple_auto.js @@ -47,7 +47,7 @@ var server = http.createServer(function(req, res) { n = parseInt(arg, 10); if (n <= 0) throw new Error('bytes called with n <= 0'); if (storedBuffer[n] === undefined) { - storedBuffer[n] = new Buffer(n); + storedBuffer[n] = Buffer.allocUnsafe(n); for (i = 0; i < n; i++) { storedBuffer[n][i] = 'C'.charCodeAt(0); } diff --git a/benchmark/net/net-c2s-cork.js b/benchmark/net/net-c2s-cork.js index 5d1c8a7495ead9..60b4542a47b1c0 100644 --- a/benchmark/net/net-c2s-cork.js +++ b/benchmark/net/net-c2s-cork.js @@ -23,8 +23,7 @@ function main(conf) { switch (type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': encoding = 'utf8'; diff --git a/benchmark/net/net-c2s.js b/benchmark/net/net-c2s.js index 370ff4f138cafd..d64a5517e8f8c7 100644 --- a/benchmark/net/net-c2s.js +++ b/benchmark/net/net-c2s.js @@ -23,8 +23,7 @@ function main(conf) { switch (type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': encoding = 'utf8'; diff --git a/benchmark/net/net-pipe.js b/benchmark/net/net-pipe.js index ea8af249a35b50..b6e95a8b75daa0 100644 --- a/benchmark/net/net-pipe.js +++ b/benchmark/net/net-pipe.js @@ -23,8 +23,7 @@ function main(conf) { switch (type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': encoding = 'utf8'; diff --git a/benchmark/net/net-s2c.js b/benchmark/net/net-s2c.js index af40d8d58d8852..2ef151f4ca46b3 100644 --- a/benchmark/net/net-s2c.js +++ b/benchmark/net/net-s2c.js @@ -23,8 +23,7 @@ function main(conf) { switch (type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': encoding = 'utf8'; diff --git a/benchmark/net/tcp-raw-c2s.js b/benchmark/net/tcp-raw-c2s.js index e13af85c6774dd..e9dd7ca662009c 100644 --- a/benchmark/net/tcp-raw-c2s.js +++ b/benchmark/net/tcp-raw-c2s.js @@ -79,8 +79,7 @@ function client() { var chunk; switch (type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': chunk = new Array(len / 2 + 1).join('ü'); diff --git a/benchmark/net/tcp-raw-pipe.js b/benchmark/net/tcp-raw-pipe.js index c05c816855e7a6..fb8da5ea41faf3 100644 --- a/benchmark/net/tcp-raw-pipe.js +++ b/benchmark/net/tcp-raw-pipe.js @@ -77,8 +77,7 @@ function client() { var chunk; switch (type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': chunk = new Array(len / 2 + 1).join('ü'); diff --git a/benchmark/net/tcp-raw-s2c.js b/benchmark/net/tcp-raw-s2c.js index 822a74c679db12..a7ef40db83ac13 100644 --- a/benchmark/net/tcp-raw-s2c.js +++ b/benchmark/net/tcp-raw-s2c.js @@ -51,8 +51,7 @@ function server() { var chunk; switch (type) { case 'buf': - chunk = new Buffer(len); - chunk.fill('x'); + chunk = Buffer.alloc(len, 'x'); break; case 'utf': chunk = new Array(len / 2 + 1).join('ü'); diff --git a/benchmark/string_decoder/string-decoder.js b/benchmark/string_decoder/string-decoder.js index b10b0a6e9cbd48..705ef841032860 100644 --- a/benchmark/string_decoder/string-decoder.js +++ b/benchmark/string_decoder/string-decoder.js @@ -9,7 +9,7 @@ var bench = common.createBenchmark(main, { n: [25e4] }); -var UTF_ALPHA = 'Blbrsyltety'; +var UTF_ALPHA = 'Blåbærsyltetøy'; var ASC_ALPHA = 'Blueberry jam'; function main(conf) { @@ -35,18 +35,18 @@ function main(conf) { for (i = 0; i < inLen; ++i) { if (i > 0 && (i % chunkLen) === 0 && !isBase64) { - chunks.push(new Buffer(str, encoding)); + chunks.push(Buffer.from(str, encoding)); str = ''; } str += alpha[i % alpha.length]; } if (str.length > 0 && !isBase64) - chunks.push(new Buffer(str, encoding)); + chunks.push(Buffer.from(str, encoding)); if (isBase64) { - str = new Buffer(str, 'utf8').toString('base64'); + str = Buffer.from(str, 'utf8').toString('base64'); while (str.length > 0) { var len = Math.min(chunkLen, str.length); - chunks.push(new Buffer(str.substring(0, len), 'utf8')); + chunks.push(Buffer.from(str.substring(0, len), 'utf8')); str = str.substring(len); } } diff --git a/benchmark/tls/throughput.js b/benchmark/tls/throughput.js index 7b545267ace7fe..d0de99e7b54b85 100644 --- a/benchmark/tls/throughput.js +++ b/benchmark/tls/throughput.js @@ -23,8 +23,7 @@ function main(conf) { var chunk; switch (type) { case 'buf': - chunk = new Buffer(size); - chunk.fill('b'); + chunk = Buffer.alloc(size, 'b'); break; case 'asc': chunk = new Array(size + 1).join('a'); @@ -74,4 +73,3 @@ function main(conf) { server.close(); } } - diff --git a/doc/api/buffer.markdown b/doc/api/buffer.markdown index 16cc82150a447c..9eba32ffadcc54 100644 --- a/doc/api/buffer.markdown +++ b/doc/api/buffer.markdown @@ -21,18 +21,112 @@ The `Buffer` class is a global within Node.js, making it unlikely that one would need to ever use `require('buffer')`. ```js -const buf1 = new Buffer(10); - // creates a buffer of length 10 +const buf1 = Buffer.alloc(10); + // Creates a zero-filled Buffer of length 10. -const buf2 = new Buffer([1,2,3]); - // creates a buffer containing [01, 02, 03] +const buf2 = Buffer.alloc(10, 1); + // Creates a Buffer of length 10, filled with 0x01. -const buf3 = new Buffer('test'); - // creates a buffer containing ASCII bytes [74, 65, 73, 74] +const buf3 = Buffer.allocUnsafe(10); + // Creates an uninitialized buffer of length 10. + // This is faster than calling Buffer.alloc() but the returned + // Buffer instance might contain old data that needs to be + // overwritten using either fill() or write(). + +const buf4 = Buffer.from([1,2,3]); + // Creates a Buffer containing [01, 02, 03]. + +const buf5 = Buffer.from('test'); + // Creates a Buffer containing ASCII bytes [74, 65, 73, 74]. + +const buf6 = Buffer.from('tést', 'utf8'); + // Creates a Buffer containing UTF8 bytes [74, c3, a9, 73, 74]. +``` + +## `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()` + +In versions of Node.js prior to v6, `Buffer` instances were created using the +`Buffer` constructor function, which allocates the returned `Buffer` +differently based on what arguments are provided: + +* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`), + allocates a new `Buffer` object of the specified size. The memory allocated + for such `Buffer` instances is *not* initialized and *can contain sensitive + data*. Such `Buffer` objects *must* be initialized *manually* by using either + [`buf.fill(0)`][] or by writing to the `Buffer` completely. While this + behavior is *intentional* to improve performance, development experience has + demonstrated that a more explicit distinction is required between creating a + fast-but-uninitialized `Buffer` versus creating a slower-but-safer `Buffer`. +* Passing a string, array, or `Buffer` as the first argument copies the + passed object's data into the `Buffer`. +* Passing an `ArrayBuffer` returns a `Buffer` that shares allocated memory with + the given `ArrayBuffer`. + +Because the behavior of `new Buffer()` changes significantly based on the type +of value passed as the first argument, applications that do not properly +validate the input arguments passed to `new Buffer()`, or that fail to +appropriately initialize newly allocated `Buffer` content, can inadvertently +introduce security and reliability issues into their code. + +To make the creation of `Buffer` objects more reliable and less error prone, +the various forms of the `new Buffer()` constructor have been **deprecated** +and replaced by separate `Buffer.from()`, `Buffer.alloc()`, and +`Buffer.allocUnsafe()` methods. + +*Developers should migrate all existing uses of the `new Buffer()` constructors +to one of these new APIs.* + +* [`Buffer.from(array)`][buffer_from_array] returns a new `Buffer` containing + a *copy* of the provided octets. +* [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][buffer_from_arraybuf] + returns a new `Buffer` that *shares* the same allocated memory as the given + `ArrayBuffer`. +* [`Buffer.from(buffer)`][buffer_from_buffer] returns a new `Buffer` + containing a *copy* of the contents of the given `Buffer`. +* [`Buffer.from(str[, encoding])`][buffer_from_string] returns a new `Buffer` + containing a *copy* of the provided string. +* [`Buffer.alloc(size[, fill[, encoding]])`][buffer_alloc] returns a "filled" + `Buffer` instance of the specified size. This method can be significantly + slower than [`Buffer.allocUnsafe(size)`][buffer_allocunsafe] but ensures that + newly created `Buffer` instances never contain old and potentially sensitive + data. +* [`Buffer.allocUnsafe(size)`][buffer_allocunsafe] returns a new `Buffer` of + the specified `size` whose content *must* be initialized using either + [`buf.fill(0)`][] or written to completely. + +`Buffer` instances returned by `Buffer.allocUnsafe(size)` *may* be allocated +off a shared internal memory pool if the `size` is less than or equal to half +`Buffer.poolSize`. + +### The `--zero-fill-buffers` command line option + +Node.js can be started using the `--zero-fill-buffers` command line option to +force all newly allocated `Buffer` and `SlowBuffer` instances created using +either `new Buffer(size)`, `Buffer.allocUnsafe(size)`, or +`new SlowBuffer(size)` to be *automatically zero-filled* upon creation. Use of +this flag *changes the default behavior* of these methods and *can have a +significant impact* on performance. Use of the `--zero-fill-buffers` option is +recommended only when absolutely necessary to enforce that newly allocated +`Buffer` instances cannot contain potentially sensitive data. -const buf4 = new Buffer('tést', 'utf8'); - // creates a buffer containing UTF8 bytes [74, c3, a9, 73, 74] ``` +$ node --zero-fill-buffers +> Buffer.allocUnsafe(5); + +``` + +### What makes `Buffer.allocUnsafe(size)` "unsafe"? + +When calling `Buffer.allocUnsafe()`, the segment of allocated memory is +*uninitialized* (it is not zeroed-out). While this design makes the allocation +of memory quite fast, the allocated segment of memory might contain old data +that is potentially sensitive. Using a `Buffer` created by +`Buffer.allocUnsafe(size)` without *completely* overwriting the memory can +allow this old data to be leaked when the `Buffer` memory is read. + +While there are clear performance advantages to using `Buffer.allocUnsafe()`, +extra care *must* be taken in order to avoid introducing security +vulnerabilities into an application. ## Buffers and Character Encodings @@ -42,7 +136,7 @@ convert back and forth between Buffers and ordinary JavaScript string objects by using an explicit encoding method. ```js -const buf = new Buffer('hello world', 'ascii'); +const buf = Buffer.from('hello world', 'ascii'); console.log(buf.toString('hex')); // prints: 68656c6c6f20776f726c64 console.log(buf.toString('base64')); @@ -83,24 +177,24 @@ existing Buffer without copying, making `Buffer#slice()` far more efficient. It is also possible to create new TypedArray instances from a `Buffer` with the following caveats: -1. The Buffer instances's memory is copied to the TypedArray, not shared. +1. The `Buffer` object's memory is copied to the TypedArray, not shared. -2. The Buffer's memory is interpreted as an array of distinct elements, and not -as a byte array of the target type. That is, -`new Uint32Array(new Buffer([1,2,3,4]))` creates a 4-element `Uint32Array` +2. The `Buffer` object's memory is interpreted as an array of distinct +elements, and not as a byte array of the target type. That is, +`new Uint32Array(Buffer.from([1,2,3,4]))` creates a 4-element `Uint32Array` with elements `[1,2,3,4]`, not a `Uint32Array` with a single element `[0x1020304]` or `[0x4030201]`. -It is possible to create a new Buffer that shares the same allocated memory as -a TypedArray instance by using the TypeArray objects `.buffer` property: +It is possible to create a new `Buffer` that shares the same allocated memory as +a TypedArray instance by using the TypeArray object's `.buffer` property: ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; -const buf1 = new Buffer(arr); // copies the buffer -const buf2 = new Buffer(arr.buffer); // shares the memory with arr; +const buf1 = Buffer.from(arr); // copies the buffer +const buf2 = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf1); // Prints: , copied buffer has only two elements @@ -114,24 +208,38 @@ console.log(buf2); // Prints: ``` -Note that when creating a Buffer using the TypeArray's `.buffer`, it is not -currently possible to use only a portion of the underlying `ArrayBuffer`. To -create a Buffer that uses only a part of the `ArrayBuffer`, use the -[`buf.slice()`][] function after the Buffer is created: +Note that when creating a `Buffer` using the TypedArray's `.buffer`, it is +possible to use only a portion of the underlying `ArrayBuffer` by passing in +`byteOffset` and `length` parameters: ```js const arr = new Uint16Array(20); -const buf = new Buffer(arr.buffer).slice(0, 16); +const buf = Buffer.from(arr.buffer, 0, 16); console.log(buf.length); // Prints: 16 ``` +The `Buffer.from()` and [`TypedArray.from()`][] (e.g.`Uint8Array.from()`) have +different signatures and implementations. Specifically, the TypedArray variants +accept a second argument that is a mapping function that is invoked on every +element of the typed array: + +* `TypedArray.from(source[, mapFn[, thisArg]])` + +The `Buffer.from()` method, however, does not support the use of a mapping +function: + +* [`Buffer.from(array)`][buffer_from_array] +* [`Buffer.from(buffer)`][buffer_from_buffer] +* [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][buffer_from_arraybuf] +* [`Buffer.from(str[, encoding])`][buffer_from_string] + ## Buffers and ES6 iteration Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax: ```js -const buf = new Buffer([1, 2, 3]); +const buf = Buffer.from([1, 2, 3]); for (var b of buf) console.log(b) @@ -152,6 +260,9 @@ It can be constructed in a variety of ways. ### new Buffer(array) + Stability: 0 - Deprecated: Use [`Buffer.from(array)`][buffer_from_array] + instead. + * `array` {Array} Allocates a new Buffer using an `array` of octets. @@ -164,6 +275,9 @@ const buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]); ### new Buffer(buffer) + Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`][buffer_from_buffer] + instead. + * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. @@ -179,15 +293,24 @@ console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` -### new Buffer(arrayBuffer) +### new Buffer(arrayBuffer[, byteOffset [, length]]) -* `arrayBuffer` - The `.buffer` property of a `TypedArray` or a `new - ArrayBuffer()` + Stability: 0 - Deprecated: Use + [`Buffer.from(arrayBuffer[, byteOffset [, length]])`][buffer_from_arraybuf] + instead. + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a + `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created Buffer will share the same allocated memory as the TypedArray. +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + ```js const arr = new Uint16Array(2); arr[0] = 5000; @@ -207,18 +330,22 @@ console.log(buf); ### new Buffer(size) + Stability: 0 - Deprecated: Use + [`Buffer.alloc(size[, fill[, encoding]])`][buffer_alloc] instead (also + see [`Buffer.allocUnsafe(size)`][buffer_allocunsafe]). + * `size` {Number} -Allocates a new Buffer of `size` bytes. The `size` must be less than +Allocates a new `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. If a `size` less than 0 is specified, a zero-length Buffer will be created. -Unlike `ArrayBuffers`, the underlying memory for Buffer instances created in -this way is not initialized. The contents of a newly created `Buffer` are -unknown and could contain sensitive data. Use [`buf.fill(0)`][] to initialize a -Buffer to zeroes. +Unlike `ArrayBuffers`, the underlying memory for `Buffer` instances created in +this way is *not initialized*. The contents of a newly created `Buffer` are +unknown and *could contain sensitive data*. Use [`buf.fill(0)`][] to initialize +a `Buffer` to zeroes. ```js const buf = new Buffer(5); @@ -232,7 +359,10 @@ console.log(buf); ### new Buffer(str[, encoding]) -* `str` {String} String to encode. + Stability: 0 - Deprecated: + Use [`Buffer.from(str[, encoding])`][buffer_from_string] instead. + +* `str` {String} string to encode. * `encoding` {String} Default: `'utf8'` Creates a new Buffer containing the given JavaScript string `str`. If @@ -250,6 +380,92 @@ console.log(buf2.toString()); // prints: this is a tést ``` +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. If a `size` less than 0 +is specified, a zero-length `Buffer` will be created. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. If a `size` less than 0 is specified, a zero-length `Buffer` will be +created. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + ### Class Method: Buffer.byteLength(string[, encoding]) * `string` {String} @@ -281,14 +497,15 @@ Compares `buf1` to `buf2` typically for the purpose of sorting arrays of Buffers. This is equivalent is calling [`buf1.compare(buf2)`][]. ```js -const arr = [Buffer('1234'), Buffer('0123')]; +const arr = [Buffer.from('1234'), Buffer.from('0123')]; arr.sort(Buffer.compare); ``` ### Class Method: Buffer.concat(list[, totalLength]) * `list` {Array} List of Buffer objects to concat -* `totalLength` {Number} Total length of the Buffers in the list when concatenated +* `totalLength` {Number} Total length of the Buffers in the list + when concatenated * Return: {Buffer} Returns a new Buffer which is the result of concatenating all the Buffers in @@ -304,9 +521,9 @@ to provide the length explicitly. Example: build a single Buffer from a list of three Buffers: ```js -const buf1 = new Buffer(10).fill(0); -const buf2 = new Buffer(14).fill(0); -const buf3 = new Buffer(18).fill(0); +const buf1 = Buffer.alloc(10); +const buf2 = Buffer.alloc(14); +const buf3 = Buffer.alloc(18); const totalLength = buf1.length + buf2.length + buf3.length; console.log(totalLength); @@ -319,6 +536,102 @@ console.log(bufA.length); // 42 ``` +### Class Method: Buffer.from(array) + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + ### Class Method: Buffer.isBuffer(obj) * `obj` {Object} @@ -347,9 +660,9 @@ Example: copy an ASCII string into a Buffer, one byte at a time: ```js const str = "Node.js"; -const buf = new Buffer(str.length); +const buf = Buffer.allocUnsafe(str.length); -for (var i = 0; i < str.length ; i++) { +for (let i = 0; i < str.length ; i++) { buf[i] = str.charCodeAt(i); } @@ -371,9 +684,9 @@ Comparison is based on the actual sequence of bytes in each Buffer. * `-1` is returned if `otherBuffer` should come *after* `buf` when sorted. ```js -const buf1 = new Buffer('ABC'); -const buf2 = new Buffer('BCD'); -const buf3 = new Buffer('ABCD'); +const buf1 = Buffer.from('ABC'); +const buf2 = Buffer.from('BCD'); +const buf3 = Buffer.from('ABCD'); console.log(buf1.compare(buf1)); // Prints: 0 @@ -405,10 +718,10 @@ Example: build two Buffers, then copy `buf1` from byte 16 through byte 19 into `buf2`, starting at the 8th byte in `buf2`. ```js -const buf1 = new Buffer(26); -const buf2 = new Buffer(26).fill('!'); +const buf1 = Buffer.allocUnsafe(26); +const buf2 = Buffer.allocUnsafe(26).fill('!'); -for (var i = 0 ; i < 26 ; i++) { +for (let i = 0 ; i < 26 ; i++) { buf1[i] = i + 97; // 97 is ASCII a } @@ -421,7 +734,7 @@ Example: Build a single Buffer, then copy data from one region to an overlapping region in the same Buffer ```js -const buf = new Buffer(26); +const buf = Buffer.allocUnsafe(26); for (var i = 0 ; i < 26 ; i++) { buf[i] = i + 97; // 97 is ASCII a @@ -441,7 +754,7 @@ Creates and returns an [iterator][] of `[index, byte]` pairs from the Buffer contents. ```js -const buf = new Buffer('buffer'); +const buf = Buffer.from('buffer'); for (var pair of buf.entries()) { console.log(pair); } @@ -463,9 +776,9 @@ Returns a boolean indicating whether `this` and `otherBuffer` have exactly the same bytes. ```js -const buf1 = new Buffer('ABC'); -const buf2 = new Buffer('414243', 'hex'); -const buf3 = new Buffer('ABCD'); +const buf1 = Buffer.from('ABC'); +const buf2 = Buffer.from('414243', 'hex'); +const buf3 = Buffer.from('ABCD'); console.log(buf1.equals(buf2)); // Prints: true @@ -488,7 +801,7 @@ This is meant as a small simplification to creating a Buffer. Allowing the creation and fill of the Buffer to be done on a single line: ```js -const b = new Buffer(50).fill('h'); +const b = Buffer.allocUnsafe(50).fill('h'); console.log(b.toString()); // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh ``` @@ -519,22 +832,22 @@ default interpreted as UTF8. Buffers will use the entire Buffer (to compare a partial Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255. ```js -const buf = new Buffer('this is a buffer'); +const buf = Buffer.from('this is a buffer'); buf.indexOf('this'); // returns 0 buf.indexOf('is'); // returns 2 -buf.indexOf(new Buffer('a buffer')); +buf.indexOf(Buffer.from('a buffer')); // returns 8 buf.indexOf(97); // ascii for 'a' // returns 8 -buf.indexOf(new Buffer('a buffer example')); +buf.indexOf(Buffer.from('a buffer example')); // returns -1 -buf.indexOf(new Buffer('a buffer example').slice(0,8)); +buf.indexOf(Buffer.from('a buffer example').slice(0,8)); // returns 8 -const utf16Buffer = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); +const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); utf16Buffer.indexOf('\u03a3', 0, 'ucs2'); // returns 4 @@ -557,19 +870,19 @@ Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255. The `byteOffset` indicates the index in `buf` where searching begins. ```js -const buf = new Buffer('this is a buffer'); +const buf = Buffer.from('this is a buffer'); buf.includes('this'); // returns true buf.includes('is'); // returns true -buf.includes(new Buffer('a buffer')); +buf.includes(Buffer.from('a buffer')); // returns true buf.includes(97); // ascii for 'a' // returns true -buf.includes(new Buffer('a buffer example')); +buf.includes(Buffer.from('a buffer example')); // returns false -buf.includes(new Buffer('a buffer example').slice(0,8)); +buf.includes(Buffer.from('a buffer example').slice(0,8)); // returns true buf.includes('this', 4); // returns false @@ -582,7 +895,7 @@ buf.includes('this', 4); Creates and returns an [iterator][] of Buffer keys (indices). ```js -const buf = new Buffer('buffer'); +const buf = Buffer.from('buffer'); for (var key of buf.keys()) { console.log(key); } @@ -605,7 +918,7 @@ Buffer. For instance, in the example below, a Buffer with 1234 bytes is allocated, but only 11 ASCII bytes are written. ```js -const buf = new Buffer(1234); +const buf = Buffer.alloc(1234); console.log(buf.length); // Prints: 1234 @@ -621,7 +934,7 @@ modify the length of a Buffer should therefore treat `length` as read-only and use [`buf.slice()`][] to create a new Buffer. ```js -var buf = new Buffer(10); +var buf = Buffer.allocUnsafe(10); buf.write('abcdefghj', 0, 'ascii'); console.log(buf.length); // Prints: 10 @@ -645,7 +958,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the `offset` to be beyond the end of the Buffer. ```js -const buf = new Buffer([1,2,3,4,5,6,7,8]); +const buf = Buffer.from([1,2,3,4,5,6,7,8]); buf.readDoubleBE(); // Returns: 8.20788039913184e-304 @@ -673,7 +986,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the `offset` to be beyond the end of the Buffer. ```js -const buf = new Buffer([1,2,3,4]); +const buf = Buffer.from([1,2,3,4]); buf.readFloatBE(); // Returns: 2.387939260590663e-38 @@ -700,7 +1013,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the Integers read from the Buffer are interpreted as two's complement signed values. ```js -const buf = new Buffer([1,-2,3,4]); +const buf = Buffer.from([1,-2,3,4]); buf.readInt8(0); // returns 1 @@ -725,7 +1038,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the Integers read from the Buffer are interpreted as two's complement signed values. ```js -const buf = new Buffer([1,-2,3,4]); +const buf = Buffer.from([1,-2,3,4]); buf.readInt16BE(); // returns 510 @@ -750,7 +1063,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the Integers read from the Buffer are interpreted as two's complement signed values. ```js -const buf = new Buffer([1,-2,3,4]); +const buf = Buffer.from([1,-2,3,4]); buf.readInt32BE(); // returns 33424132 @@ -771,7 +1084,7 @@ and interprets the result as a two's complement signed value. Supports up to 48 bits of accuracy. For example: ```js -const buf = new Buffer(6); +const buf = Buffer.allocUnsafe(6); buf.writeUInt16LE(0x90ab, 0); buf.writeUInt32LE(0x12345678, 2); buf.readIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) @@ -796,7 +1109,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the `offset` to be beyond the end of the Buffer. ```js -const buf = new Buffer([1,-2,3,4]); +const buf = Buffer.from([1,-2,3,4]); buf.readUInt8(0); // returns 1 @@ -821,7 +1134,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the Example: ```js -const buf = new Buffer([0x3, 0x4, 0x23, 0x42]); +const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]); buf.readUInt16BE(0); // Returns: 0x0304 @@ -854,7 +1167,7 @@ Setting `noAssert` to `true` skips validation of the `offset`. This allows the Example: ```js -const buf = new Buffer([0x3, 0x4, 0x23, 0x42]); +const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]); buf.readUInt32BE(0); // Returns: 0x03042342 @@ -875,7 +1188,7 @@ and interprets the result as an unsigned integer. Supports up to 48 bits of accuracy. For example: ```js -const buf = new Buffer(6); +const buf = Buffer.allocUnsafe(6); buf.writeUInt16LE(0x90ab, 0); buf.writeUInt32LE(0x12345678, 2); buf.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits) @@ -904,7 +1217,7 @@ Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer. ```js -const buf1 = new Buffer(26); +const buf1 = Buffer.allocUnsafe(26); for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97; // 97 is ASCII a @@ -922,7 +1235,7 @@ Specifying negative indexes causes the slice to be generated relative to the end of the Buffer rather than the beginning. ```js -const buf = new Buffer('buffer'); +const buf = Buffer.from('buffer'); buf.slice(-6, -1).toString(); // Returns 'buffe', equivalent to buf.slice(0, 5) @@ -943,7 +1256,7 @@ Decodes and returns a string from the Buffer data using the specified character set `encoding`. ```js -const buf = new Buffer(26); +const buf = Buffer.allocUnsafe(26); for (var i = 0 ; i < 26 ; i++) { buf[i] = i + 97; // 97 is ASCII a } @@ -967,7 +1280,7 @@ implicitly calls this function when stringifying a Buffer instance. Example: ```js -const buf = new Buffer('test'); +const buf = Buffer.from('test'); const json = JSON.stringify(buf); console.log(json); @@ -975,7 +1288,7 @@ console.log(json); const copy = JSON.parse(json, (key, value) => { return value && value.type === 'Buffer' - ? new Buffer(value.data) + ? Buffer.from(value.data) : value; }); @@ -991,7 +1304,7 @@ Creates and returns an [iterator][] for Buffer values (bytes). This function is called automatically when the Buffer is used in a `for..of` statement. ```js -const buf = new Buffer('buffer'); +const buf = Buffer.from('buffer'); for (var value of buf.values()) { console.log(value); } @@ -1030,7 +1343,7 @@ string will be written however, it will not write only partially encoded characters. ```js -const buf = new Buffer(256); +const buf = Buffer.allocUnsafe(256); const len = buf.write('\u00bd + \u00bc = \u00be', 0); console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); // Prints: 12 bytes: ½ + ¼ = ¾ @@ -1056,7 +1369,7 @@ should not be used unless you are certain of correctness. Example: ```js -const buf = new Buffer(8); +const buf = Buffer.allocUnsafe(8); buf.writeDoubleBE(0xdeadbeefcafebabe, 0); console.log(buf); @@ -1089,7 +1402,7 @@ should not be used unless you are certain of correctness. Example: ```js -const buf = new Buffer(4); +const buf = Buffer.allocUnsafe(4); buf.writeFloatBE(0xcafebabe, 0); console.log(buf); @@ -1119,7 +1432,7 @@ should not be used unless you are certain of correctness. The `value` is interpreted and written as a two's complement signed integer. ```js -const buf = new Buffer(2); +const buf = Buffer.allocUnsafe(2); buf.writeInt8(2, 0); buf.writeInt8(-2, 1); console.log(buf); @@ -1146,7 +1459,7 @@ should not be used unless you are certain of correctness. The `value` is interpreted and written as a two's complement signed integer. ```js -const buf = new Buffer(4); +const buf = Buffer.allocUnsafe(4); buf.writeInt16BE(0x0102,0); buf.writeInt16LE(0x0304,2); console.log(buf); @@ -1173,7 +1486,7 @@ should not be used unless you are certain of correctness. The `value` is interpreted and written as a two's complement signed integer. ```js -const buf = new Buffer(8); +const buf = Buffer.allocUnsafe(8); buf.writeInt32BE(0x01020304,0); buf.writeInt32LE(0x05060708,4); console.log(buf); @@ -1193,12 +1506,12 @@ Writes `value` to the Buffer at the specified `offset` and `byteLength`. Supports up to 48 bits of accuracy. For example: ```js -const buf1 = new Buffer(6); +const buf1 = Buffer.allocUnsafe(6); buf1.writeUIntBE(0x1234567890ab, 0, 6); console.log(buf1); // Prints: -const buf2 = new Buffer(6); +const buf2 = Buffer.allocUnsafe(6); buf2.writeUIntLE(0x1234567890ab, 0, 6); console.log(buf2); // Prints: @@ -1227,7 +1540,7 @@ should not be used unless you are certain of correctness. Example: ```js -const buf = new Buffer(4); +const buf = Buffer.allocUnsafe(4); buf.writeUInt8(0x3, 0); buf.writeUInt8(0x4, 1); buf.writeUInt8(0x23, 2); @@ -1257,7 +1570,7 @@ should not be used unless you are certain of correctness. Example: ```js -const buf = new Buffer(4); +const buf = Buffer.allocUnsafe(4); buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); @@ -1291,7 +1604,7 @@ should not be used unless you are certain of correctness. Example: ```js -const buf = new Buffer(4); +const buf = Buffer.allocUnsafe(4); buf.writeUInt32BE(0xfeedface, 0); console.log(buf); @@ -1316,7 +1629,7 @@ Writes `value` to the Buffer at the specified `offset` and `byteLength`. Supports up to 48 bits of accuracy. For example: ```js -const buf = new Buffer(6); +const buf = Buffer.allocUnsafe(6); buf.writeUIntBE(0x1234567890ab, 0, 6); console.log(buf); // Prints: @@ -1358,7 +1671,7 @@ const store = []; socket.on('readable', () => { var data = socket.read(); // allocate for retained data - var sb = new SlowBuffer(10); + var sb = SlowBuffer(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); @@ -1368,8 +1681,34 @@ socket.on('readable', () => { Use of `SlowBuffer` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. -[`Array#includes()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes +### new SlowBuffer(size) + +* `size` Number + +Allocates a new `SlowBuffer` of `size` bytes. The `size` must be less than +or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. If a `size` less than 0 is specified, a zero-length `SlowBuffer` will be +created. + +The underlying memory for `SlowBuffer` instances is *not initialized*. The +contents of a newly created `SlowBuffer` are unknown and could contain +sensitive data. Use [`buf.fill(0)`][] to initialize a `SlowBuffer` to zeroes. + +```js +const SlowBuffer = require('buffer').SlowBuffer; +const buf = new SlowBuffer(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols [`Array#indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf +[`Array#includes()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes [`buf.entries()`]: #buffer_buf_entries [`buf.fill(0)`]: #buffer_buf_fill_value_offset_end [`buf.keys()`]: #buffer_buf_keys @@ -1380,5 +1719,11 @@ has observed undue memory retention in their applications. [`RangeError`]: errors.html#errors_class_rangeerror [`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length [`util.inspect()`]: util.html#util_util_inspect_object_options -[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols [RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5 +[buffer_from_array]: #buffer_class_method_buffer_from_array +[buffer_from_buffer]: #buffer_class_method_buffer_from_buffer +[buffer_from_arraybuf]: #buffer_class_method_buffer_from_arraybuffer +[buffer_from_string]: #buffer_class_method_buffer_from_str_encoding +[buffer_allocunsafe]: #buffer_class_method_buffer_allocraw_size +[buffer_alloc]: #buffer_class_method_buffer_alloc_size_fill_encoding +[`TypedArray.from()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from diff --git a/doc/node.1 b/doc/node.1 index 0f3933a58d5855..e6f00b61e4f3bd 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -66,6 +66,9 @@ and servers. --prof-process process v8 profiler output generated using --prof + --zero-fill-buffers automatically zero-fill all newly allocated + Buffer and SlowBuffer instances + --v8-options print v8 command line options --tls-cipher-list=list use an alternative default TLS cipher list diff --git a/lib/_debugger.js b/lib/_debugger.js index 7ec91d1e002c22..b183f2b586d6c8 100644 --- a/lib/_debugger.js +++ b/lib/_debugger.js @@ -108,7 +108,7 @@ Protocol.prototype.execute = function(d) { var resRawByteLength = Buffer.byteLength(res.raw, 'utf8'); if (resRawByteLength - this.bodyStartByteIndex >= this.contentLength) { - var buf = new Buffer(resRawByteLength); + var buf = Buffer.allocUnsafe(resRawByteLength); buf.write(res.raw, 0, resRawByteLength, 'utf8'); res.body = buf.slice(this.bodyStartByteIndex, diff --git a/lib/_http_client.js b/lib/_http_client.js index 2b37ad1a82159e..25beb97ba90e09 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -97,7 +97,7 @@ function ClientRequest(options, cb) { if (options.auth && !this.getHeader('Authorization')) { //basic auth this.setHeader('Authorization', 'Basic ' + - new Buffer(options.auth).toString('base64')); + Buffer.from(options.auth).toString('base64')); } if (method === 'GET' || diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index ec5e078412768b..77bfe4ba77d416 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -526,7 +526,7 @@ OutgoingMessage.prototype.addTrailers = function(headers) { }; -const crlf_buf = new Buffer('\r\n'); +const crlf_buf = Buffer.from('\r\n'); OutgoingMessage.prototype.end = function(data, encoding, callback) { diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 1ad85dc81c8b5c..338bf2a7539bfc 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -103,7 +103,7 @@ Readable.prototype.push = function(chunk, encoding) { if (!state.objectMode && typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); + chunk = Buffer.from(chunk, encoding); encoding = ''; } } @@ -866,7 +866,7 @@ function fromList(n, state) { if (stringMode) ret = ''; else - ret = new Buffer(n); + ret = Buffer.allocUnsafe(n); var c = 0; for (var i = 0, l = list.length; i < l && c < n; i++) { diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 9efce66a3cc46f..b6e621fd1e3b78 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -252,7 +252,7 @@ function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); + chunk = Buffer.from(chunk, encoding); } return chunk; } diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index 42b7f283bc7d87..bc293f04178d70 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -23,7 +23,7 @@ function SlabBuffer() { SlabBuffer.prototype.create = function create() { this.isFull = false; - this.pool = new Buffer(tls.SLAB_BUFFER_SIZE); + this.pool = Buffer.allocUnsafe(tls.SLAB_BUFFER_SIZE); this.offset = 0; this.remaining = this.pool.length; }; diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 697fbfa3e560d8..0f52363e10354d 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -602,7 +602,7 @@ TLSSocket.prototype.setServername = function(name) { TLSSocket.prototype.setSession = function(session) { if (typeof session === 'string') - session = new Buffer(session, 'binary'); + session = Buffer.from(session, 'binary'); this._handle.setSession(session); }; @@ -845,7 +845,7 @@ Server.prototype._getServerData = function() { Server.prototype._setServerData = function(data) { - this.setTicketKeys(new Buffer(data.ticketKeys, 'hex')); + this.setTicketKeys(Buffer.from(data.ticketKeys, 'hex')); }; diff --git a/lib/assert.js b/lib/assert.js index c2b6699c66fd0e..61aba557ec2e07 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -173,7 +173,7 @@ function _deepEqual(actual, expected, strict) { // If both values are instances of typed arrays, wrap them in // a Buffer each to increase performance } else if (ArrayBuffer.isView(actual) && ArrayBuffer.isView(expected)) { - return compare(new Buffer(actual), new Buffer(expected)) === 0; + return compare(Buffer.from(actual), Buffer.from(expected)) === 0; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified diff --git a/lib/buffer.js b/lib/buffer.js index 766a82c2f21f0e..01a8f303e1b92c 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -9,6 +9,8 @@ exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; exports.kMaxLength = binding.kMaxLength; +const kFromErrorMsg = 'First argument must be a string, Buffer, ' + + 'ArrayBuffer, Array, or array-like object.'; Buffer.poolSize = 8 * 1024; var poolSize, poolOffset, allocPool; @@ -42,34 +44,90 @@ function alignPool() { } } - -function Buffer(arg, encoding) { +/** + * The Buffer() construtor is "soft deprecated" ... that is, it is deprecated + * in the documentation and should not be used moving forward. Rather, + * developers should use one of the three new factory APIs: Buffer.from(), + * Buffer.allocUnsafe() or Buffer.alloc() based on their specific needs. There + * is no hard deprecation because of the extent to which the Buffer constructor + * is used in the ecosystem currently -- a hard deprecation would introduce too + * much breakage at this time. It's not likely that the Buffer constructors + * would ever actually be removed. + **/ +function Buffer(arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { - if (typeof encoding === 'string') { + if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ); } - // If less than zero, or NaN. - if (arg < 0 || arg !== arg) - arg = 0; - return allocate(arg); - } - - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(arg, encoding); + return Buffer.allocUnsafe(arg); } - - // Unusual. - return fromObject(arg); + return Buffer.from(arg, encodingOrOffset, length); } +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function(value, encodingOrOffset, length) { + if (typeof value === 'number') + throw new TypeError('"value" argument must not be a number'); + + if (value instanceof ArrayBuffer) + return fromArrayBuffer(value, encodingOrOffset, length); + + if (typeof value === 'string') + return fromString(value, encodingOrOffset); + + return fromObject(value); +}; + Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); Object.setPrototypeOf(Buffer, Uint8Array); +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function(size, fill, encoding) { + if (typeof size !== 'number') + throw new TypeError('"size" argument must be a number'); + if (size <= 0) + return createBuffer(size); + if (fill !== undefined) { + // Since we are filling anyway, don't zero fill initially. + flags[kNoZeroFill] = 1; + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' ? + createBuffer(size).fill(fill, encoding) : + createBuffer(size).fill(fill); + } + flags[kNoZeroFill] = 0; + return createBuffer(size); +}; + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer + * instance. If `--zero-fill-buffers` is set, will zero-fill the buffer. + **/ +Buffer.allocUnsafe = function(size) { + if (typeof size !== 'number') + throw new TypeError('"size" argument must be a number'); + if (size > 0) + flags[kNoZeroFill] = 1; + return allocate(size); +}; +// If --zero-fill-buffers command line argument is set, a zero-filled +// buffer is returned. function SlowBuffer(length) { if (+length != length) length = 0; @@ -108,6 +166,9 @@ function fromString(string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'; + if (!Buffer.isEncoding(encoding)) + throw new TypeError('"encoding" must be a valid string encoding'); + var length = byteLength(string, encoding); if (length >= (Buffer.poolSize >>> 1)) return binding.createFromString(string, encoding); @@ -129,6 +190,16 @@ function fromArrayLike(obj) { return b; } +function fromArrayBuffer(obj, byteOffset, length) { + byteOffset >>>= 0; + + if (typeof length === 'undefined') + return binding.createFromArrayBuffer(obj, byteOffset); + + length >>>= 0; + return binding.createFromArrayBuffer(obj, byteOffset, length); +} + function fromObject(obj) { if (obj instanceof Buffer) { const b = allocate(obj.length); @@ -140,26 +211,20 @@ function fromObject(obj) { return b; } - if (obj == null) { - throw new TypeError('Must start with number, buffer, array or string'); - } - - if (obj instanceof ArrayBuffer) { - return binding.createFromArrayBuffer(obj); - } - - if (obj.buffer instanceof ArrayBuffer || 'length' in obj) { - if (typeof obj.length !== 'number' || obj.length !== obj.length) { - return allocate(0); + if (obj) { + if (obj.buffer instanceof ArrayBuffer || 'length' in obj) { + if (typeof obj.length !== 'number' || obj.length !== obj.length) { + return allocate(0); + } + return fromArrayLike(obj); } - return fromArrayLike(obj); - } - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } } - throw new TypeError('Must start with number, buffer, array or string'); + throw new TypeError(kFromErrorMsg); } @@ -215,7 +280,7 @@ Buffer.concat = function(list, length) { throw new TypeError('"list" argument must be an Array of Buffers'); if (list.length === 0) - return new Buffer(0); + return Buffer.alloc(0); if (length === undefined) { length = 0; @@ -225,7 +290,7 @@ Buffer.concat = function(list, length) { length = length >>> 0; } - var buffer = new Buffer(length); + var buffer = Buffer.allocUnsafe(length); var pos = 0; for (let i = 0; i < list.length; i++) { var buf = list[i]; @@ -454,7 +519,7 @@ function slowIndexOf(buffer, val, byteOffset, encoding) { case 'ascii': case 'hex': return binding.indexOfBuffer( - buffer, Buffer(val, encoding), byteOffset, encoding); + buffer, Buffer.from(val, encoding), byteOffset, encoding); default: if (loweredCase) { @@ -518,6 +583,11 @@ Buffer.prototype.fill = function fill(val, start, end, encoding) { if (code < 256) val = code; } + if (val.length === 0) { + // Previously, if val === '', the Buffer would not fill, + // which is rather surprising. + val = 0; + } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } diff --git a/lib/child_process.js b/lib/child_process.js index e682aed5aede07..d6b029b7a50c22 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -422,7 +422,7 @@ function spawnSync(/*file, args, options*/) { if (Buffer.isBuffer(input)) pipe.input = input; else if (typeof input === 'string') - pipe.input = new Buffer(input, options.encoding); + pipe.input = Buffer.from(input, options.encoding); else throw new TypeError(util.format( 'stdio[%d] should be Buffer or string not %s', diff --git a/lib/crypto.js b/lib/crypto.js index 89bafdfddd49cd..3e440a61fcd710 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -33,7 +33,7 @@ function toBuf(str, encoding) { if (typeof str === 'string') { if (encoding === 'buffer' || !encoding) encoding = 'utf8'; - return new Buffer(str, encoding); + return Buffer.from(str, encoding); } return str; } diff --git a/lib/dgram.js b/lib/dgram.js index 4b6e7fa6e27666..0c92e361c0eae7 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -252,7 +252,7 @@ Socket.prototype.sendto = function(buffer, function sliceBuffer(buffer, offset, length) { if (typeof buffer === 'string') - buffer = new Buffer(buffer); + buffer = Buffer.from(buffer); else if (!(buffer instanceof Buffer)) throw new TypeError('First argument must be a buffer or string'); @@ -267,7 +267,7 @@ function fixBuffer(buffer) { for (var i = 0, l = buffer.length; i < l; i++) { var buf = buffer[i]; if (typeof buf === 'string') - buffer[i] = new Buffer(buf); + buffer[i] = Buffer.from(buf); else if (!(buf instanceof Buffer)) return false; } @@ -318,7 +318,7 @@ Socket.prototype.send = function(buffer, if (!Array.isArray(buffer)) { if (typeof buffer === 'string') { - buffer = [ new Buffer(buffer) ]; + buffer = [ Buffer.from(buffer) ]; } else if (!(buffer instanceof Buffer)) { throw new TypeError('First argument must be a buffer or a string'); } else { diff --git a/lib/fs.js b/lib/fs.js index 9aa4eaa6a562ec..487f19d305d23d 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -321,7 +321,7 @@ ReadFileContext.prototype.read = function() { var length; if (this.size === 0) { - buffer = this.buffer = new SlowBuffer(kReadFileBufferLength); + buffer = this.buffer = SlowBuffer(kReadFileBufferLength); offset = 0; length = kReadFileBufferLength; } else { @@ -389,7 +389,7 @@ function readFileAfterStat(err, st) { return context.close(err); } - context.buffer = new SlowBuffer(size); + context.buffer = SlowBuffer(size); context.read(); } @@ -486,7 +486,7 @@ fs.readFileSync = function(path, options) { } else { threw = true; try { - buffer = new Buffer(size); + buffer = Buffer.allocUnsafe(size); threw = false; } finally { if (threw && !isUserFd) fs.closeSync(fd); @@ -504,7 +504,7 @@ fs.readFileSync = function(path, options) { } else { // the kernel lies about many files. // Go ahead and try to read some bytes. - buffer = new Buffer(8192); + buffer = Buffer.allocUnsafe(8192); bytesRead = fs.readSync(fd, buffer, 0, 8192); if (bytesRead) { buffers.push(buffer.slice(0, bytesRead)); @@ -635,7 +635,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) { position = arguments[2]; length = arguments[1]; - buffer = new Buffer(length); + buffer = Buffer.allocUnsafe(length); offset = 0; callback = function(err, bytesRead) { @@ -695,7 +695,7 @@ fs.readSync = function(fd, buffer, offset, length, position) { position = arguments[2]; length = arguments[1]; - buffer = new Buffer(length); + buffer = Buffer.allocUnsafe(length); offset = 0; } @@ -1260,8 +1260,8 @@ fs.writeFile = function(path, data, options, callback_) { }); function writeFd(fd, isUserFd) { - var buffer = (data instanceof Buffer) ? data : new Buffer('' + data, - options.encoding || 'utf8'); + var buffer = (data instanceof Buffer) ? + data : Buffer.from('' + data, options.encoding || 'utf8'); var position = /a/.test(flag) ? null : 0; writeAll(fd, isUserFd, buffer, 0, buffer.length, position, callback); @@ -1284,7 +1284,7 @@ fs.writeFileSync = function(path, data, options) { var fd = isUserFd ? path : fs.openSync(path, flag, options.mode); if (!(data instanceof Buffer)) { - data = new Buffer('' + data, options.encoding || 'utf8'); + data = Buffer.from('' + data, options.encoding || 'utf8'); } var offset = 0; var length = data.length; @@ -1738,7 +1738,7 @@ fs.realpath = function realpath(p, cache, cb) { var pool; function allocNewPool(poolSize) { - pool = new Buffer(poolSize); + pool = Buffer.allocUnsafe(poolSize); pool.used = 0; } @@ -2108,7 +2108,7 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) { // Change strings to buffers. SLOW if (typeof data === 'string') { - data = new Buffer(data, encoding); + data = Buffer.from(data, encoding); } fs.writeSync(this.fd, data, 0, data.length); diff --git a/lib/internal/v8_prof_polyfill.js b/lib/internal/v8_prof_polyfill.js index 755f8f0d65d1fb..145b09e345bfa6 100644 --- a/lib/internal/v8_prof_polyfill.js +++ b/lib/internal/v8_prof_polyfill.js @@ -60,7 +60,7 @@ try { process.exit(1); } const fd = fs.openSync(logFile, 'r'); -const buf = new Buffer(4096); +const buf = Buffer.allocUnsafe(4096); const dec = new (require('string_decoder').StringDecoder)('utf-8'); var line = ''; versionCheck(); diff --git a/lib/net.js b/lib/net.js index b0436143f11bc1..b3af78e447a8e8 100644 --- a/lib/net.js +++ b/lib/net.js @@ -724,7 +724,7 @@ function createWriteReq(req, handle, data, encoding) { return handle.writeUcs2String(req, data); default: - return handle.writeBuffer(req, new Buffer(data, encoding)); + return handle.writeBuffer(req, Buffer.from(data, encoding)); } } diff --git a/lib/querystring.js b/lib/querystring.js index b56ad77012d035..29fc6552c5c9a2 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -8,7 +8,7 @@ const Buffer = require('buffer').Buffer; // a safe fast alternative to decodeURIComponent QueryString.unescapeBuffer = function(s, decodeSpaces) { - var out = new Buffer(s.length); + var out = Buffer.allocUnsafe(s.length); var state = 0; var n, m, hexchar; diff --git a/lib/string_decoder.js b/lib/string_decoder.js index a0bfd535ad8895..16803921573885 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -44,7 +44,7 @@ const StringDecoder = exports.StringDecoder = function(encoding) { // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); + this.charBuffer = Buffer.allocUnsafe(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. diff --git a/lib/tls.js b/lib/tls.js index 245afb6bdc7561..1f7dcf39a158aa 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -33,7 +33,7 @@ exports.getCiphers = function() { // Convert protocols array into valid OpenSSL protocols list // ("\x06spdy/2\x08http/1.1\x08http/1.0") function convertProtocols(protocols) { - var buff = new Buffer(protocols.reduce(function(p, c) { + var buff = Buffer.allocUnsafe(protocols.reduce(function(p, c) { return p + 1 + Buffer.byteLength(c); }, 0)); @@ -67,7 +67,7 @@ exports.convertALPNProtocols = function(protocols, out) { // If it's already a Buffer - store it if (protocols instanceof Buffer) { // copy new buffer not to be modified by user - out.ALPNProtocols = new Buffer(protocols); + out.ALPNProtocols = Buffer.from(protocols); } }; diff --git a/lib/zlib.js b/lib/zlib.js index 3e6f7b187632f2..0028c35d7923eb 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -230,7 +230,7 @@ function zlibBuffer(engine, buffer, callback) { function zlibBufferSync(engine, buffer) { if (typeof buffer === 'string') - buffer = new Buffer(buffer); + buffer = Buffer.from(buffer); if (!(buffer instanceof Buffer)) throw new TypeError('Not a string or buffer'); @@ -378,7 +378,7 @@ function Zlib(opts, mode) { strategy, opts.dictionary); - this._buffer = new Buffer(this._chunkSize); + this._buffer = Buffer.allocUnsafe(this._chunkSize); this._offset = 0; this._closed = false; this._level = level; @@ -426,7 +426,7 @@ Zlib.prototype.reset = function() { // This is the _flush function called by the transform class, // internally, when the last chunk has been written. Zlib.prototype._flush = function(callback) { - this._transform(new Buffer(0), '', callback); + this._transform(Buffer.alloc(0), '', callback); }; Zlib.prototype.flush = function(kind, callback) { @@ -449,7 +449,7 @@ Zlib.prototype.flush = function(kind, callback) { } } else { this._flushFlag = kind; - this.write(new Buffer(0), '', callback); + this.write(Buffer.alloc(0), '', callback); } }; @@ -580,7 +580,7 @@ Zlib.prototype._processChunk = function(chunk, flushFlag, cb) { if (availOutAfter === 0 || self._offset >= self._chunkSize) { availOutBefore = self._chunkSize; self._offset = 0; - self._buffer = new Buffer(self._chunkSize); + self._buffer = Buffer.allocUnsafe(self._chunkSize); } if (availOutAfter === 0) { diff --git a/src/node.cc b/src/node.cc index 976237efe214f3..679643ebf883b0 100644 --- a/src/node.cc +++ b/src/node.cc @@ -955,7 +955,9 @@ Local WinapiErrnoException(Isolate* isolate, void* ArrayBufferAllocator::Allocate(size_t size) { - if (env_ == nullptr || !env_->array_buffer_allocator_info()->no_zero_fill()) + if (env_ == nullptr || + !env_->array_buffer_allocator_info()->no_zero_fill() || + zero_fill_all_buffers) return calloc(size, 1); env_->array_buffer_allocator_info()->reset_fill_flag(); return malloc(size); @@ -3312,6 +3314,8 @@ static void PrintHelp() { "snapshots\n" " --prof-process process v8 profiler output generated\n" " using --prof\n" + " --zero-fill-buffers automatically zero-fill all newly allocated\n" + " Buffer and SlowBuffer instances\n" " --v8-options print v8 command line options\n" #if HAVE_OPENSSL " --tls-cipher-list=val use an alternative default TLS cipher list\n" @@ -3455,6 +3459,8 @@ static void ParseArgs(int* argc, } else if (strcmp(arg, "--prof-process") == 0) { prof_process = true; short_circuit = true; + } else if (strcmp(arg, "--zero-fill-buffers") == 0) { + zero_fill_all_buffers = true; } else if (strcmp(arg, "--v8-options") == 0) { new_v8_argv[new_v8_argc] = "--help"; new_v8_argc += 1; diff --git a/src/node_buffer.cc b/src/node_buffer.cc index aecc6874d80c6d..6720f2c9379c13 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -48,7 +48,14 @@ CHECK_NOT_OOB(end <= end_max); \ size_t length = end - start; +#define BUFFER_MALLOC(length) \ + zero_fill_all_buffers ? calloc(length, 1) : malloc(length) + namespace node { + +// if true, all Buffer and SlowBuffer instances will automatically zero-fill +bool zero_fill_all_buffers = false; + namespace Buffer { using v8::ArrayBuffer; @@ -74,7 +81,6 @@ using v8::Uint8Array; using v8::Value; using v8::WeakCallbackInfo; - class CallbackInfo { public: static inline void Free(char* data, void* hint); @@ -210,7 +216,7 @@ MaybeLocal New(Isolate* isolate, // nullptr for zero-sized allocation requests. Normalize by always using // a nullptr. if (length > 0) { - data = static_cast(malloc(length)); + data = static_cast(BUFFER_MALLOC(length)); if (data == nullptr) return Local(); @@ -256,7 +262,7 @@ MaybeLocal New(Environment* env, size_t length) { void* data; if (length > 0) { - data = malloc(length); + data = BUFFER_MALLOC(length); if (data == nullptr) return Local(); } else { @@ -419,7 +425,20 @@ void CreateFromArrayBuffer(const FunctionCallbackInfo& args) { if (!args[0]->IsArrayBuffer()) return env->ThrowTypeError("argument is not an ArrayBuffer"); Local ab = args[0].As(); - Local ui = Uint8Array::New(ab, 0, ab->ByteLength()); + + size_t ab_length = ab->ByteLength(); + size_t offset; + size_t max_length; + + CHECK_NOT_OOB(ParseArrayIndex(args[1], 0, &offset)); + CHECK_NOT_OOB(ParseArrayIndex(args[2], ab_length - offset, &max_length)); + + if (offset >= ab_length) + return env->ThrowRangeError("'offset' is out of bounds"); + if (max_length > ab_length - offset) + return env->ThrowRangeError("'length' is out of bounds"); + + Local ui = Uint8Array::New(ab, offset, max_length); Maybe mb = ui->SetPrototype(env->context(), env->buffer_prototype_object()); if (!mb.FromMaybe(false)) diff --git a/src/node_buffer.h b/src/node_buffer.h index 2bcf245f3920ad..2ecfab33a3f186 100644 --- a/src/node_buffer.h +++ b/src/node_buffer.h @@ -5,6 +5,9 @@ #include "v8.h" namespace node { + +extern bool zero_fill_all_buffers; + namespace Buffer { static const unsigned int kMaxLength = diff --git a/test/disabled/test-debug-brk-file.js b/test/disabled/test-debug-brk-file.js index 4b5823f56a64e1..ee20577ded6145 100644 --- a/test/disabled/test-debug-brk-file.js +++ b/test/disabled/test-debug-brk-file.js @@ -56,7 +56,7 @@ function debug_client_connect() { } if (msg.headers && Buffer.byteLength(tmpBuf) >= msg.contentLength) { try { - var b = Buffer(tmpBuf); + var b = Buffer.from(tmpBuf); var body = b.toString('utf8', 0, msg.contentLength); tmpBuf = b.toString('utf8', msg.contentLength, b.length); diff --git a/test/disabled/test-dgram-send-error.js b/test/disabled/test-dgram-send-error.js index 1ed594a389a8c4..0b68af3a0ff08a 100644 --- a/test/disabled/test-dgram-send-error.js +++ b/test/disabled/test-dgram-send-error.js @@ -13,8 +13,7 @@ var assert = require('assert'), common = require('../common'), dgram = require('dgram'); -var buf = new Buffer(1024); -buf.fill(42); +var buf = Buffer.alloc(1024, 42); var packetsReceived = 0, packetsSent = 0; diff --git a/test/disabled/test-fs-largefile.js b/test/disabled/test-fs-largefile.js index 498bfa45a06dda..fb0058b358a5c3 100644 --- a/test/disabled/test-fs-largefile.js +++ b/test/disabled/test-fs-largefile.js @@ -10,9 +10,9 @@ var path = require('path'), fs.truncateSync(fd, offset); assert.equal(fs.statSync(filepath).size, offset); -var writeBuf = new Buffer(message); +var writeBuf = Buffer.from(message); fs.writeSync(fd, writeBuf, 0, writeBuf.length, offset); -var readBuf = new Buffer(writeBuf.length); +var readBuf = Buffer.allocUnsafe(writeBuf.length); fs.readSync(fd, readBuf, 0, readBuf.length, offset); assert.equal(readBuf.toString(), message); fs.readSync(fd, readBuf, 0, 1, 0); @@ -32,4 +32,3 @@ fs.close(fd); process.on('exit', function() { fs.unlinkSync(filepath); }); - diff --git a/test/disabled/test-sendfd.js b/test/disabled/test-sendfd.js index b48acadba51768..d473cd93c33153 100644 --- a/test/disabled/test-sendfd.js +++ b/test/disabled/test-sendfd.js @@ -91,7 +91,7 @@ var srv = net.createServer(function(s) { var str = JSON.stringify(DATA) + '\n'; DATA.ord = DATA.ord + 1; - var buf = new buffer.Buffer(str.length); + var buf = buffer.Buffer.allocUnsafe(str.length); buf.write(JSON.stringify(DATA) + '\n', 'utf8'); s.write(str, 'utf8', pipeFDs[1]); diff --git a/test/fixtures/GH-892-request.js b/test/fixtures/GH-892-request.js index 498a537a12784c..96c355857fea4c 100644 --- a/test/fixtures/GH-892-request.js +++ b/test/fixtures/GH-892-request.js @@ -22,7 +22,7 @@ var req = https.request(options, function(res) { res.resume(); }); -req.end(new Buffer(bytesExpected)); +req.end(Buffer.allocUnsafe(bytesExpected)); process.on('exit', function() { assert.ok(gotResponse); diff --git a/test/fixtures/print-chars-from-buffer.js b/test/fixtures/print-chars-from-buffer.js index 53ca743b06ef0a..fc902a896fe54f 100644 --- a/test/fixtures/print-chars-from-buffer.js +++ b/test/fixtures/print-chars-from-buffer.js @@ -2,7 +2,7 @@ var assert = require('assert'); var n = parseInt(process.argv[2]); -var b = new Buffer(n); +var b = Buffer.allocUnsafe(n); for (var i = 0; i < n; i++) { b[i] = 100; } diff --git a/test/internet/test-dgram-broadcast-multi-process.js b/test/internet/test-dgram-broadcast-multi-process.js index 344f6506afdeb1..d7e7f819ae2696 100644 --- a/test/internet/test-dgram-broadcast-multi-process.js +++ b/test/internet/test-dgram-broadcast-multi-process.js @@ -9,10 +9,10 @@ const fork = require('child_process').fork; const LOCAL_BROADCAST_HOST = '255.255.255.255'; const TIMEOUT = common.platformTimeout(5000); const messages = [ - new Buffer('First message to send'), - new Buffer('Second message to send'), - new Buffer('Third message to send'), - new Buffer('Fourth message to send') + Buffer.from('First message to send'), + Buffer.from('Second message to send'), + Buffer.from('Third message to send'), + Buffer.from('Fourth message to send') ]; if (common.inFreeBSDJail) { diff --git a/test/internet/test-dgram-multicast-multi-process.js b/test/internet/test-dgram-multicast-multi-process.js index 69d7bbe3173787..54df63ba7697e1 100644 --- a/test/internet/test-dgram-multicast-multi-process.js +++ b/test/internet/test-dgram-multicast-multi-process.js @@ -6,10 +6,10 @@ const fork = require('child_process').fork; const LOCAL_BROADCAST_HOST = '224.0.0.114'; const TIMEOUT = common.platformTimeout(5000); const messages = [ - new Buffer('First message to send'), - new Buffer('Second message to send'), - new Buffer('Third message to send'), - new Buffer('Fourth message to send') + Buffer.from('First message to send'), + Buffer.from('Second message to send'), + Buffer.from('Third message to send'), + Buffer.from('Fourth message to send') ]; const workers = {}; const listeners = 3; diff --git a/test/internet/test-dgram-send-cb-quelches-error.js b/test/internet/test-dgram-send-cb-quelches-error.js index dbbd8fc9fd7f58..64b354c3eb3bfc 100644 --- a/test/internet/test-dgram-send-cb-quelches-error.js +++ b/test/internet/test-dgram-send-cb-quelches-error.js @@ -6,7 +6,7 @@ var dgram = require('dgram'); var dns = require('dns'); var socket = dgram.createSocket('udp4'); -var buffer = new Buffer('gary busey'); +var buffer = Buffer.from('gary busey'); dns.setServers([]); diff --git a/test/parallel/test-async-wrap-check-providers.js b/test/parallel/test-async-wrap-check-providers.js index 3a2c80d9cbe173..cd95e7a0f9df57 100644 --- a/test/parallel/test-async-wrap-check-providers.js +++ b/test/parallel/test-async-wrap-check-providers.js @@ -81,7 +81,7 @@ net.createServer(function(c) { }); dgram.createSocket('udp4').bind(common.PORT, function() { - this.send(new Buffer(2), 0, 2, common.PORT, '::', () => { + this.send(Buffer.allocUnsafe(2), 0, 2, common.PORT, '::', () => { this.close(); }); }); diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js new file mode 100644 index 00000000000000..b88b12f7f67526 --- /dev/null +++ b/test/parallel/test-buffer-alloc.js @@ -0,0 +1,1442 @@ +'use strict'; +var common = require('../common'); +var assert = require('assert'); + +var Buffer = require('buffer').Buffer; +var SlowBuffer = require('buffer').SlowBuffer; + +// counter to ensure unique value is always copied +var cntr = 0; + +var b = Buffer.allocUnsafe(1024); + +console.log('b.length == %d', b.length); +assert.strictEqual(1024, b.length); + +b[0] = -1; +assert.strictEqual(b[0], 255); + +for (let i = 0; i < 1024; i++) { + b[i] = i % 256; +} + +for (let i = 0; i < 1024; i++) { + assert.strictEqual(i % 256, b[i]); +} + +var c = Buffer.allocUnsafe(512); +console.log('c.length == %d', c.length); +assert.strictEqual(512, c.length); + +var d = Buffer.from([]); +assert.strictEqual(0, d.length); + +var ui32 = new Uint32Array(4).fill(42); +var e = Buffer.from(ui32); +assert.deepEqual(ui32, e); + +// First check Buffer#fill() works as expected. + +assert.throws(function() { + Buffer.allocUnsafe(8).fill('a', -1); +}); + +assert.throws(function() { + Buffer.allocUnsafe(8).fill('a', 0, 9); +}); + +// Make sure this doesn't hang indefinitely. +Buffer.allocUnsafe(8).fill(''); +Buffer.alloc(8, ''); + +{ + const buf = Buffer.alloc(64, 10); + for (let i = 0; i < buf.length; i++) + assert.equal(buf[i], 10); + + buf.fill(11, 0, buf.length >> 1); + for (let i = 0; i < buf.length >> 1; i++) + assert.equal(buf[i], 11); + for (let i = (buf.length >> 1) + 1; i < buf.length; i++) + assert.equal(buf[i], 10); + + buf.fill('h'); + for (let i = 0; i < buf.length; i++) + assert.equal('h'.charCodeAt(0), buf[i]); + + buf.fill(0); + for (let i = 0; i < buf.length; i++) + assert.equal(0, buf[i]); + + buf.fill(null); + for (let i = 0; i < buf.length; i++) + assert.equal(0, buf[i]); + + buf.fill(1, 16, 32); + for (let i = 0; i < 16; i++) + assert.equal(0, buf[i]); + for (let i = 16; i < 32; i++) + assert.equal(1, buf[i]); + for (let i = 32; i < buf.length; i++) + assert.equal(0, buf[i]); +} + +{ + const buf = Buffer.alloc(10, 'abc'); + assert.equal(buf.toString(), 'abcabcabca'); + buf.fill('է'); + assert.equal(buf.toString(), 'էէէէէ'); +} + +{ + // copy 512 bytes, from 0 to 512. + b.fill(++cntr); + c.fill(++cntr); + const copied = b.copy(c, 0, 0, 512); + console.log('copied %d bytes from b into c', copied); + assert.strictEqual(512, copied); + for (let i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); + } +} + +{ + // copy c into b, without specifying sourceEnd + b.fill(++cntr); + c.fill(++cntr); + const copied = c.copy(b, 0, 0); + console.log('copied %d bytes from c into b w/o sourceEnd', copied); + assert.strictEqual(c.length, copied); + for (let i = 0; i < c.length; i++) { + assert.strictEqual(c[i], b[i]); + } +} + +{ + // copy c into b, without specifying sourceStart + b.fill(++cntr); + c.fill(++cntr); + const copied = c.copy(b, 0); + console.log('copied %d bytes from c into b w/o sourceStart', copied); + assert.strictEqual(c.length, copied); + for (let i = 0; i < c.length; i++) { + assert.strictEqual(c[i], b[i]); + } +} + +{ + // copy longer buffer b to shorter c without targetStart + b.fill(++cntr); + c.fill(++cntr); + const copied = b.copy(c); + console.log('copied %d bytes from b into c w/o targetStart', copied); + assert.strictEqual(c.length, copied); + for (let i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); + } +} + +{ + // copy starting near end of b to c + b.fill(++cntr); + c.fill(++cntr); + const copied = b.copy(c, 0, b.length - Math.floor(c.length / 2)); + console.log('copied %d bytes from end of b into beginning of c', copied); + assert.strictEqual(Math.floor(c.length / 2), copied); + for (let i = 0; i < Math.floor(c.length / 2); i++) { + assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]); + } + for (let i = Math.floor(c.length / 2) + 1; i < c.length; i++) { + assert.strictEqual(c[c.length - 1], c[i]); + } +} + +{ + // try to copy 513 bytes, and check we don't overrun c + b.fill(++cntr); + c.fill(++cntr); + const copied = b.copy(c, 0, 0, 513); + console.log('copied %d bytes from b trying to overrun c', copied); + assert.strictEqual(c.length, copied); + for (let i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); + } +} + +{ + // copy 768 bytes from b into b + b.fill(++cntr); + b.fill(++cntr, 256); + const copied = b.copy(b, 0, 256, 1024); + console.log('copied %d bytes from b into b', copied); + assert.strictEqual(768, copied); + for (let i = 0; i < b.length; i++) { + assert.strictEqual(cntr, b[i]); + } +} + +// copy string longer than buffer length (failure will segfault) +var bb = Buffer.allocUnsafe(10); +bb.fill('hello crazy world'); + + +// try to copy from before the beginning of b +assert.doesNotThrow(() => { b.copy(c, 0, 100, 10); }); + +// copy throws at negative sourceStart +assert.throws(function() { + Buffer.allocUnsafe(5).copy(Buffer.allocUnsafe(5), 0, -1); +}, RangeError); + +{ + // check sourceEnd resets to targetEnd if former is greater than the latter + b.fill(++cntr); + c.fill(++cntr); + const copied = b.copy(c, 0, 0, 1025); + console.log('copied %d bytes from b into c', copied); + for (let i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); + } +} + +// throw with negative sourceEnd +console.log('test copy at negative sourceEnd'); +assert.throws(function() { + b.copy(c, 0, 0, -1); +}, RangeError); + +// when sourceStart is greater than sourceEnd, zero copied +assert.equal(b.copy(c, 0, 100, 10), 0); + +// when targetStart > targetLength, zero copied +assert.equal(b.copy(c, 512, 0, 10), 0); + +var caught_error; + +// invalid encoding for Buffer.toString +caught_error = null; +try { + b.toString('invalid'); +} catch (err) { + caught_error = err; +} +assert.strictEqual('Unknown encoding: invalid', caught_error.message); + +// invalid encoding for Buffer.write +caught_error = null; +try { + b.write('test string', 0, 5, 'invalid'); +} catch (err) { + caught_error = err; +} +assert.strictEqual('Unknown encoding: invalid', caught_error.message); + +// try to create 0-length buffers +Buffer.from(''); +Buffer.from('', 'ascii'); +Buffer.from('', 'binary'); +Buffer.alloc(0); +Buffer.allocUnsafe(0); + +// try to write a 0-length string beyond the end of b +assert.throws(function() { + b.write('', 2048); +}, RangeError); + +// throw when writing to negative offset +assert.throws(function() { + b.write('a', -1); +}, RangeError); + +// throw when writing past bounds from the pool +assert.throws(function() { + b.write('a', 2048); +}, RangeError); + +// throw when writing to negative offset +assert.throws(function() { + b.write('a', -1); +}, RangeError); + +// try to copy 0 bytes worth of data into an empty buffer +b.copy(Buffer.alloc(0), 0, 0, 0); + +// try to copy 0 bytes past the end of the target buffer +b.copy(Buffer.alloc(0), 1, 1, 1); +b.copy(Buffer.alloc(1), 1, 1, 1); + +// try to copy 0 bytes from past the end of the source buffer +b.copy(Buffer.alloc(1), 0, 2048, 2048); + +const rangeBuffer = Buffer.from('abc'); + +// if start >= buffer's length, empty string will be returned +assert.equal(rangeBuffer.toString('ascii', 3), ''); +assert.equal(rangeBuffer.toString('ascii', +Infinity), ''); +assert.equal(rangeBuffer.toString('ascii', 3.14, 3), ''); +assert.equal(rangeBuffer.toString('ascii', 'Infinity', 3), ''); + +// if end <= 0, empty string will be returned +assert.equal(rangeBuffer.toString('ascii', 1, 0), ''); +assert.equal(rangeBuffer.toString('ascii', 1, -1.2), ''); +assert.equal(rangeBuffer.toString('ascii', 1, -100), ''); +assert.equal(rangeBuffer.toString('ascii', 1, -Infinity), ''); + +// if start < 0, start will be taken as zero +assert.equal(rangeBuffer.toString('ascii', -1, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', -1.99, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', -Infinity, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', '-1', 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', '-1.99', 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', '-Infinity', 3), 'abc'); + +// if start is an invalid integer, start will be taken as zero +assert.equal(rangeBuffer.toString('ascii', 'node.js', 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', {}, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', [], 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', NaN, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', null, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', undefined, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', false, 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', '', 3), 'abc'); + +// but, if start is an integer when coerced, then it will be coerced and used. +assert.equal(rangeBuffer.toString('ascii', '-1', 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', '1', 3), 'bc'); +assert.equal(rangeBuffer.toString('ascii', '-Infinity', 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', '3', 3), ''); +assert.equal(rangeBuffer.toString('ascii', Number(3), 3), ''); +assert.equal(rangeBuffer.toString('ascii', '3.14', 3), ''); +assert.equal(rangeBuffer.toString('ascii', '1.99', 3), 'bc'); +assert.equal(rangeBuffer.toString('ascii', '-1.99', 3), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 1.99, 3), 'bc'); +assert.equal(rangeBuffer.toString('ascii', true, 3), 'bc'); + +// if end > buffer's length, end will be taken as buffer's length +assert.equal(rangeBuffer.toString('ascii', 0, 5), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, 6.99), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, Infinity), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, '5'), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, '6.99'), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, 'Infinity'), 'abc'); + +// if end is an invalid integer, end will be taken as buffer's length +assert.equal(rangeBuffer.toString('ascii', 0, 'node.js'), ''); +assert.equal(rangeBuffer.toString('ascii', 0, {}), ''); +assert.equal(rangeBuffer.toString('ascii', 0, NaN), ''); +assert.equal(rangeBuffer.toString('ascii', 0, undefined), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, null), ''); +assert.equal(rangeBuffer.toString('ascii', 0, []), ''); +assert.equal(rangeBuffer.toString('ascii', 0, false), ''); +assert.equal(rangeBuffer.toString('ascii', 0, ''), ''); + +// but, if end is an integer when coerced, then it will be coerced and used. +assert.equal(rangeBuffer.toString('ascii', 0, '-1'), ''); +assert.equal(rangeBuffer.toString('ascii', 0, '1'), 'a'); +assert.equal(rangeBuffer.toString('ascii', 0, '-Infinity'), ''); +assert.equal(rangeBuffer.toString('ascii', 0, '3'), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, Number(3)), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, '3.14'), 'abc'); +assert.equal(rangeBuffer.toString('ascii', 0, '1.99'), 'a'); +assert.equal(rangeBuffer.toString('ascii', 0, '-1.99'), ''); +assert.equal(rangeBuffer.toString('ascii', 0, 1.99), 'a'); +assert.equal(rangeBuffer.toString('ascii', 0, true), 'a'); + +// try toString() with a object as a encoding +assert.equal(rangeBuffer.toString({toString: function() { + return 'ascii'; +}}), 'abc'); + +// testing for smart defaults and ability to pass string values as offset +var writeTest = Buffer.from('abcdes'); +writeTest.write('n', 'ascii'); +writeTest.write('o', '1', 'ascii'); +writeTest.write('d', '2', 'ascii'); +writeTest.write('e', 3, 'ascii'); +writeTest.write('j', 4, 'ascii'); +assert.equal(writeTest.toString(), 'nodejs'); + +// ASCII slice test +{ + const asciiString = 'hello world'; + + for (let i = 0; i < asciiString.length; i++) { + b[i] = asciiString.charCodeAt(i); + } + const asciiSlice = b.toString('ascii', 0, asciiString.length); + assert.equal(asciiString, asciiSlice); +} + +{ + const asciiString = 'hello world'; + const offset = 100; + + const written = b.write(asciiString, offset, 'ascii'); + assert.equal(asciiString.length, written); + const asciiSlice = b.toString('ascii', offset, offset + asciiString.length); + assert.equal(asciiString, asciiSlice); +} + +{ + const asciiString = 'hello world'; + const offset = 100; + + const sliceA = b.slice(offset, offset + asciiString.length); + const sliceB = b.slice(offset, offset + asciiString.length); + for (let i = 0; i < asciiString.length; i++) { + assert.equal(sliceA[i], sliceB[i]); + } +} + +// UTF-8 slice test + +var utf8String = '¡hέlló wôrld!'; +var offset = 100; + +b.write(utf8String, 0, Buffer.byteLength(utf8String), 'utf8'); +var utf8Slice = b.toString('utf8', 0, Buffer.byteLength(utf8String)); +assert.equal(utf8String, utf8Slice); + +var written = b.write(utf8String, offset, 'utf8'); +assert.equal(Buffer.byteLength(utf8String), written); +utf8Slice = b.toString('utf8', offset, offset + Buffer.byteLength(utf8String)); +assert.equal(utf8String, utf8Slice); + +var sliceA = b.slice(offset, offset + Buffer.byteLength(utf8String)); +var sliceB = b.slice(offset, offset + Buffer.byteLength(utf8String)); +for (let i = 0; i < Buffer.byteLength(utf8String); i++) { + assert.equal(sliceA[i], sliceB[i]); +} + +{ + const slice = b.slice(100, 150); + assert.equal(50, slice.length); + for (let i = 0; i < 50; i++) { + assert.equal(b[100 + i], slice[i]); + } +} + +{ + // make sure only top level parent propagates from allocPool + const b = Buffer.allocUnsafe(5); + const c = b.slice(0, 4); + const d = c.slice(0, 2); + assert.equal(b.parent, c.parent); + assert.equal(b.parent, d.parent); +} + +{ + // also from a non-pooled instance + const b = new SlowBuffer(5); + const c = b.slice(0, 4); + const d = c.slice(0, 2); + assert.equal(c.parent, d.parent); +} + +{ + // Bug regression test + const testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語 + const buffer = Buffer.allocUnsafe(32); + const size = buffer.write(testValue, 0, 'utf8'); + console.log('bytes written to buffer: ' + size); + const slice = buffer.toString('utf8', 0, size); + assert.equal(slice, testValue); +} + +{ + // Test triple slice + const a = Buffer.allocUnsafe(8); + for (let i = 0; i < 8; i++) a[i] = i; + const b = a.slice(4, 8); + assert.equal(4, b[0]); + assert.equal(5, b[1]); + assert.equal(6, b[2]); + assert.equal(7, b[3]); + const c = b.slice(2, 4); + assert.equal(6, c[0]); + assert.equal(7, c[1]); +} + +{ + const d = Buffer.from([23, 42, 255]); + assert.equal(d.length, 3); + assert.equal(d[0], 23); + assert.equal(d[1], 42); + assert.equal(d[2], 255); + assert.deepEqual(d, Buffer.from(d)); +} + +{ + const e = Buffer.from('über'); + console.error('uber: \'%s\'', e.toString()); + assert.deepEqual(e, Buffer.from([195, 188, 98, 101, 114])); +} + +{ + const f = Buffer.from('über', 'ascii'); + console.error('f.length: %d (should be 4)', f.length); + assert.deepEqual(f, Buffer.from([252, 98, 101, 114])); +} + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + { + const f = Buffer.from('über', encoding); + console.error('f.length: %d (should be 8)', f.length); + assert.deepEqual(f, Buffer.from([252, 0, 98, 0, 101, 0, 114, 0])); + } + + { + const f = Buffer.from('привет', encoding); + console.error('f.length: %d (should be 12)', f.length); + assert.deepEqual(f, + Buffer.from([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4])); + assert.equal(f.toString(encoding), 'привет'); + } + + { + const f = Buffer.from([0, 0, 0, 0, 0]); + assert.equal(f.length, 5); + const size = f.write('あいうえお', encoding); + console.error('bytes written to buffer: %d (should be 4)', size); + assert.equal(size, 4); + assert.deepEqual(f, Buffer.from([0x42, 0x30, 0x44, 0x30, 0x00])); + } +}); + +{ + const f = Buffer.from('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D) + assert.equal(f.length, 4); + assert.deepEqual(f, Buffer.from('3DD84DDC', 'hex')); +} + + +var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; +var g = Buffer.from(arrayIsh); +assert.deepEqual(g, Buffer.from([0, 1, 2, 3])); +var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4}; +g = Buffer.from(strArrayIsh); +assert.deepEqual(g, Buffer.from([0, 1, 2, 3])); + + +// +// Test toString('base64') +// +assert.equal('TWFu', (Buffer.from('Man')).toString('base64')); + +{ + // test that regular and URL-safe base64 both work + const expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff]; + assert.deepEqual(Buffer.from('//++/++/++//', 'base64'), + Buffer.from(expected)); + assert.deepEqual(Buffer.from('__--_--_--__', 'base64'), + Buffer.from(expected)); +} + +{ + // big example + const quote = 'Man is distinguished, not only by his reason, but by this ' + + 'singular passion from other animals, which is a lust ' + + 'of the mind, that by a perseverance of delight in the ' + + 'continued and indefatigable generation of knowledge, exceeds ' + + 'the short vehemence of any carnal pleasure.'; + const expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb' + + '24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBh' + + 'bmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnk' + + 'gYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIG' + + 'FuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBle' + + 'GNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVh' + + 'c3VyZS4='; + assert.equal(expected, (Buffer.from(quote)).toString('base64')); + + let b = Buffer.allocUnsafe(1024); + let bytesWritten = b.write(expected, 0, 'base64'); + assert.equal(quote.length, bytesWritten); + assert.equal(quote, b.toString('ascii', 0, quote.length)); + + // check that the base64 decoder ignores whitespace + const expectedWhite = expected.slice(0, 60) + ' \n' + + expected.slice(60, 120) + ' \n' + + expected.slice(120, 180) + ' \n' + + expected.slice(180, 240) + ' \n' + + expected.slice(240, 300) + '\n' + + expected.slice(300, 360) + '\n'; + b = Buffer.allocUnsafe(1024); + bytesWritten = b.write(expectedWhite, 0, 'base64'); + assert.equal(quote.length, bytesWritten); + assert.equal(quote, b.toString('ascii', 0, quote.length)); + + // check that the base64 decoder on the constructor works + // even in the presence of whitespace. + b = Buffer.from(expectedWhite, 'base64'); + assert.equal(quote.length, b.length); + assert.equal(quote, b.toString('ascii', 0, quote.length)); + + // check that the base64 decoder ignores illegal chars + const expectedIllegal = expected.slice(0, 60) + ' \x80' + + expected.slice(60, 120) + ' \xff' + + expected.slice(120, 180) + ' \x00' + + expected.slice(180, 240) + ' \x98' + + expected.slice(240, 300) + '\x03' + + expected.slice(300, 360); + b = Buffer.from(expectedIllegal, 'base64'); + assert.equal(quote.length, b.length); + assert.equal(quote, b.toString('ascii', 0, quote.length)); +} + +assert.equal(Buffer.from('', 'base64').toString(), ''); +assert.equal(Buffer.from('K', 'base64').toString(), ''); + +// multiple-of-4 with padding +assert.equal(Buffer.from('Kg==', 'base64').toString(), '*'); +assert.equal(Buffer.from('Kio=', 'base64').toString(), '**'); +assert.equal(Buffer.from('Kioq', 'base64').toString(), '***'); +assert.equal(Buffer.from('KioqKg==', 'base64').toString(), '****'); +assert.equal(Buffer.from('KioqKio=', 'base64').toString(), '*****'); +assert.equal(Buffer.from('KioqKioq', 'base64').toString(), '******'); +assert.equal(Buffer.from('KioqKioqKg==', 'base64').toString(), '*******'); +assert.equal(Buffer.from('KioqKioqKio=', 'base64').toString(), '********'); +assert.equal(Buffer.from('KioqKioqKioq', 'base64').toString(), '*********'); +assert.equal(Buffer.from('KioqKioqKioqKg==', 'base64').toString(), + '**********'); +assert.equal(Buffer.from('KioqKioqKioqKio=', 'base64').toString(), + '***********'); +assert.equal(Buffer.from('KioqKioqKioqKioq', 'base64').toString(), + '************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKg==', 'base64').toString(), + '*************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKio=', 'base64').toString(), + '**************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioq', 'base64').toString(), + '***************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKg==', 'base64').toString(), + '****************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKio=', 'base64').toString(), + '*****************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioq', 'base64').toString(), + '******************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(), + '*******************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(), + '********************'); + +// no padding, not a multiple of 4 +assert.equal(Buffer.from('Kg', 'base64').toString(), '*'); +assert.equal(Buffer.from('Kio', 'base64').toString(), '**'); +assert.equal(Buffer.from('KioqKg', 'base64').toString(), '****'); +assert.equal(Buffer.from('KioqKio', 'base64').toString(), '*****'); +assert.equal(Buffer.from('KioqKioqKg', 'base64').toString(), '*******'); +assert.equal(Buffer.from('KioqKioqKio', 'base64').toString(), '********'); +assert.equal(Buffer.from('KioqKioqKioqKg', 'base64').toString(), '**********'); +assert.equal(Buffer.from('KioqKioqKioqKio', 'base64').toString(), + '***********'); +assert.equal(Buffer.from('KioqKioqKioqKioqKg', 'base64').toString(), + '*************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKio', 'base64').toString(), + '**************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKg', 'base64').toString(), + '****************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKio', 'base64').toString(), + '*****************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(), + '*******************'); +assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(), + '********************'); + +// handle padding graciously, multiple-of-4 or not +assert.equal(Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', + 'base64').length, 32); +assert.equal(Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', + 'base64').length, 32); +assert.equal(Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', + 'base64').length, 32); +assert.equal(Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', + 'base64').length, 31); +assert.equal(Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', + 'base64').length, 31); +assert.equal(Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', + 'base64').length, 31); + +// This string encodes single '.' character in UTF-16 +var dot = Buffer.from('//4uAA==', 'base64'); +assert.equal(dot[0], 0xff); +assert.equal(dot[1], 0xfe); +assert.equal(dot[2], 0x2e); +assert.equal(dot[3], 0x00); +assert.equal(dot.toString('base64'), '//4uAA=='); + +{ + // Writing base64 at a position > 0 should not mangle the result. + // + // https://github.com/joyent/node/issues/402 + const segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh']; + const b = Buffer.allocUnsafe(64); + let pos = 0; + + for (let i = 0; i < segments.length; ++i) { + pos += b.write(segments[i], pos, 'base64'); + } + assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!'); +} + +// Regression test for https://github.com/nodejs/node/issues/3496. +assert.equal(Buffer.from('=bad'.repeat(1e4), 'base64').length, 0); + +{ + // Creating buffers larger than pool size. + const l = Buffer.poolSize + 5; + let s = ''; + for (let i = 0; i < l; i++) { + s += 'h'; + } + + const b = Buffer.from(s); + + for (let i = 0; i < l; i++) { + assert.equal('h'.charCodeAt(0), b[i]); + } + + const sb = b.toString(); + assert.equal(sb.length, s.length); + assert.equal(sb, s); +} + +{ + // Single argument slice + const b = Buffer.from('abcde'); + assert.equal('bcde', b.slice(1).toString()); +} + +// slice(0,0).length === 0 +assert.equal(0, Buffer.from('hello').slice(0, 0).length); + +// test hex toString +console.log('Create hex string from buffer'); +var hexb = Buffer.allocUnsafe(256); +for (let i = 0; i < 256; i++) { + hexb[i] = i; +} +var hexStr = hexb.toString('hex'); +assert.equal(hexStr, + '000102030405060708090a0b0c0d0e0f' + + '101112131415161718191a1b1c1d1e1f' + + '202122232425262728292a2b2c2d2e2f' + + '303132333435363738393a3b3c3d3e3f' + + '404142434445464748494a4b4c4d4e4f' + + '505152535455565758595a5b5c5d5e5f' + + '606162636465666768696a6b6c6d6e6f' + + '707172737475767778797a7b7c7d7e7f' + + '808182838485868788898a8b8c8d8e8f' + + '909192939495969798999a9b9c9d9e9f' + + 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' + + 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' + + 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' + + 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' + + 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' + + 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'); + +console.log('Create buffer from hex string'); +var hexb2 = Buffer.from(hexStr, 'hex'); +for (let i = 0; i < 256; i++) { + assert.equal(hexb2[i], hexb[i]); +} + +{ + // test an invalid slice end. + console.log('Try to slice off the end of the buffer'); + const b = Buffer.from([1, 2, 3, 4, 5]); + const b2 = b.toString('hex', 1, 10000); + const b3 = b.toString('hex', 1, 5); + const b4 = b.toString('hex', 1); + assert.equal(b2, b3); + assert.equal(b2, b4); +} + +function buildBuffer(data) { + if (Array.isArray(data)) { + var buffer = Buffer.allocUnsafe(data.length); + data.forEach(function(v, k) { + buffer[k] = v; + }); + return buffer; + } + return null; +} + +var x = buildBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]); + +console.log(x.inspect()); +assert.equal('', x.inspect()); + +{ + const z = x.slice(4); + console.log(z.inspect()); + console.log(z.length); + assert.equal(5, z.length); + assert.equal(0x6f, z[0]); + assert.equal(0xa3, z[1]); + assert.equal(0x62, z[2]); + assert.equal(0x61, z[3]); + assert.equal(0x72, z[4]); +} + +{ + const z = x.slice(0); + console.log(z.inspect()); + console.log(z.length); + assert.equal(z.length, x.length); +} + +{ + const z = x.slice(0, 4); + console.log(z.inspect()); + console.log(z.length); + assert.equal(4, z.length); + assert.equal(0x81, z[0]); + assert.equal(0xa3, z[1]); +} + +{ + const z = x.slice(0, 9); + console.log(z.inspect()); + console.log(z.length); + assert.equal(9, z.length); +} + +{ + const z = x.slice(1, 4); + console.log(z.inspect()); + console.log(z.length); + assert.equal(3, z.length); + assert.equal(0xa3, z[0]); +} + +{ + const z = x.slice(2, 4); + console.log(z.inspect()); + console.log(z.length); + assert.equal(2, z.length); + assert.equal(0x66, z[0]); + assert.equal(0x6f, z[1]); +} + +assert.equal(0, Buffer.from('hello').slice(0, 0).length); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + const b = Buffer.allocUnsafe(10); + b.write('あいうえお', encoding); + assert.equal(b.toString(encoding), 'あいうえお'); +}); + +{ + // Binary encoding should write only one byte per character. + const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]); + let s = String.fromCharCode(0xffff); + b.write(s, 0, 'binary'); + assert.equal(0xff, b[0]); + assert.equal(0xad, b[1]); + assert.equal(0xbe, b[2]); + assert.equal(0xef, b[3]); + s = String.fromCharCode(0xaaee); + b.write(s, 0, 'binary'); + assert.equal(0xee, b[0]); + assert.equal(0xad, b[1]); + assert.equal(0xbe, b[2]); + assert.equal(0xef, b[3]); +} + +{ + // #1210 Test UTF-8 string includes null character + let buf = Buffer.from('\0'); + assert.equal(buf.length, 1); + buf = Buffer.from('\0\0'); + assert.equal(buf.length, 2); +} + +{ + const buf = Buffer.allocUnsafe(2); + let written = buf.write(''); // 0byte + assert.equal(written, 0); + written = buf.write('\0'); // 1byte (v8 adds null terminator) + assert.equal(written, 1); + written = buf.write('a\0'); // 1byte * 2 + assert.equal(written, 2); + written = buf.write('あ'); // 3bytes + assert.equal(written, 0); + written = buf.write('\0あ'); // 1byte + 3bytes + assert.equal(written, 1); + written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes + assert.equal(written, 2); +} + +{ + const buf = Buffer.allocUnsafe(10); + written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator) + assert.equal(written, 9); + written = buf.write('あいう\0'); // 3bytes * 3 + 1byte + assert.equal(written, 10); +} + +{ + // #243 Test write() with maxLength + const buf = Buffer.allocUnsafe(4); + buf.fill(0xFF); + let written = buf.write('abcd', 1, 2, 'utf8'); + console.log(buf); + assert.equal(written, 2); + assert.equal(buf[0], 0xFF); + assert.equal(buf[1], 0x61); + assert.equal(buf[2], 0x62); + assert.equal(buf[3], 0xFF); + + buf.fill(0xFF); + written = buf.write('abcd', 1, 4); + console.log(buf); + assert.equal(written, 3); + assert.equal(buf[0], 0xFF); + assert.equal(buf[1], 0x61); + assert.equal(buf[2], 0x62); + assert.equal(buf[3], 0x63); + + buf.fill(0xFF); + written = buf.write('abcd', 1, 2, 'utf8'); + console.log(buf); + assert.equal(written, 2); + assert.equal(buf[0], 0xFF); + assert.equal(buf[1], 0x61); + assert.equal(buf[2], 0x62); + assert.equal(buf[3], 0xFF); + + buf.fill(0xFF); + written = buf.write('abcdef', 1, 2, 'hex'); + console.log(buf); + assert.equal(written, 2); + assert.equal(buf[0], 0xFF); + assert.equal(buf[1], 0xAB); + assert.equal(buf[2], 0xCD); + assert.equal(buf[3], 0xFF); + + ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + buf.fill(0xFF); + written = buf.write('abcd', 0, 2, encoding); + console.log(buf); + assert.equal(written, 2); + assert.equal(buf[0], 0x61); + assert.equal(buf[1], 0x00); + assert.equal(buf[2], 0xFF); + assert.equal(buf[3], 0xFF); + }); +} + +{ + // test offset returns are correct + const b = Buffer.allocUnsafe(16); + assert.equal(4, b.writeUInt32LE(0, 0)); + assert.equal(6, b.writeUInt16LE(0, 4)); + assert.equal(7, b.writeUInt8(0, 6)); + assert.equal(8, b.writeInt8(0, 7)); + assert.equal(16, b.writeDoubleLE(0, 8)); +} + +{ + // test unmatched surrogates not producing invalid utf8 output + // ef bf bd = utf-8 representation of unicode replacement character + // see https://codereview.chromium.org/121173009/ + const buf = Buffer.from('ab\ud800cd', 'utf8'); + assert.equal(buf[0], 0x61); + assert.equal(buf[1], 0x62); + assert.equal(buf[2], 0xef); + assert.equal(buf[3], 0xbf); + assert.equal(buf[4], 0xbd); + assert.equal(buf[5], 0x63); + assert.equal(buf[6], 0x64); +} + +{ + // test for buffer overrun + const buf = Buffer.from([0, 0, 0, 0, 0]); // length: 5 + var sub = buf.slice(0, 4); // length: 4 + written = sub.write('12345', 'binary'); + assert.equal(written, 4); + assert.equal(buf[4], 0); +} + +// Check for fractional length args, junk length args, etc. +// https://github.com/joyent/node/issues/1758 + +// Call .fill() first, stops valgrind warning about uninitialized memory reads. +Buffer.allocUnsafe(3.3).fill().toString(); + // throws bad argument error in commit 43cb4ec +Buffer.alloc(3.3).fill().toString(); +assert.equal(Buffer.allocUnsafe(-1).length, 0); +assert.equal(Buffer.allocUnsafe(NaN).length, 0); +assert.equal(Buffer.allocUnsafe(3.3).length, 3); +assert.equal(Buffer.from({length: 3.3}).length, 3); +assert.equal(Buffer.from({length: 'BAM'}).length, 0); + +// Make sure that strings are not coerced to numbers. +assert.equal(Buffer.from('99').length, 2); +assert.equal(Buffer.from('13.37').length, 5); + +// Ensure that the length argument is respected. +'ascii utf8 hex base64 binary'.split(' ').forEach(function(enc) { + assert.equal(Buffer.allocUnsafe(1).write('aaaaaa', 0, 1, enc), 1); +}); + +{ + // Regression test, guard against buffer overrun in the base64 decoder. + const a = Buffer.allocUnsafe(3); + const b = Buffer.from('xxx'); + a.write('aaaaaaaa', 'base64'); + assert.equal(b.toString(), 'xxx'); +} + +// issue GH-3416 +Buffer.from(Buffer.allocUnsafe(0), 0, 0); + +[ 'hex', + 'utf8', + 'utf-8', + 'ascii', + 'binary', + 'base64', + 'ucs2', + 'ucs-2', + 'utf16le', + 'utf-16le' ].forEach(function(enc) { + assert.equal(Buffer.isEncoding(enc), true); + }); + +[ 'utf9', + 'utf-7', + 'Unicode-FTW', + 'new gnu gun' ].forEach(function(enc) { + assert.equal(Buffer.isEncoding(enc), false); + }); + + +// GH-5110 +(function() { + const buffer = Buffer.from('test'); + const string = JSON.stringify(buffer); + + assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + + assert.deepEqual(buffer, JSON.parse(string, function(key, value) { + return value && value.type === 'Buffer' + ? Buffer.from(value.data) + : value; + })); +})(); + +// issue GH-7849 +(function() { + var buf = Buffer.from('test'); + var json = JSON.stringify(buf); + var obj = JSON.parse(json); + var copy = Buffer.from(obj); + + assert(buf.equals(copy)); +})(); + +// issue GH-4331 +assert.throws(function() { + Buffer.allocUnsafe(0xFFFFFFFF); +}, RangeError); +assert.throws(function() { + Buffer.allocUnsafe(0xFFFFFFFFF); +}, RangeError); + + +// attempt to overflow buffers, similar to previous bug in array buffers +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.readFloatLE(0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.writeFloatLE(0.0, 0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.readFloatLE(0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.writeFloatLE(0.0, 0xffffffff); +}, RangeError); + + +// ensure negative values can't get past offset +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.readFloatLE(-1); +}, RangeError); + +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.writeFloatLE(0.0, -1); +}, RangeError); + +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.readFloatLE(-1); +}, RangeError); + +assert.throws(function() { + var buf = Buffer.allocUnsafe(8); + buf.writeFloatLE(0.0, -1); +}, RangeError); + +// offset checks +{ + const buf = Buffer.allocUnsafe(0); + + assert.throws(function() { buf.readUInt8(0); }, RangeError); + assert.throws(function() { buf.readInt8(0); }, RangeError); +} + +{ + const buf = Buffer.from([0xFF]); + + assert.equal(buf.readUInt8(0), 255); + assert.equal(buf.readInt8(0), -1); +} + +[16, 32].forEach(function(bits) { + var buf = Buffer.allocUnsafe(bits / 8 - 1); + + assert.throws(function() { buf['readUInt' + bits + 'BE'](0); }, + RangeError, + 'readUInt' + bits + 'BE'); + + assert.throws(function() { buf['readUInt' + bits + 'LE'](0); }, + RangeError, + 'readUInt' + bits + 'LE'); + + assert.throws(function() { buf['readInt' + bits + 'BE'](0); }, + RangeError, + 'readInt' + bits + 'BE()'); + + assert.throws(function() { buf['readInt' + bits + 'LE'](0); }, + RangeError, + 'readInt' + bits + 'LE()'); +}); + +[16, 32].forEach(function(bits) { + var buf = Buffer.from([0xFF, 0xFF, 0xFF, 0xFF]); + + assert.equal(buf['readUInt' + bits + 'BE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readUInt' + bits + 'LE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'BE'](0), + (0xFFFFFFFF >> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'LE'](0), + (0xFFFFFFFF >> (32 - bits))); +}); + +// test for common read(U)IntLE/BE +(function() { + var buf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); + + assert.equal(buf.readUIntLE(0, 1), 0x01); + assert.equal(buf.readUIntBE(0, 1), 0x01); + assert.equal(buf.readUIntLE(0, 3), 0x030201); + assert.equal(buf.readUIntBE(0, 3), 0x010203); + assert.equal(buf.readUIntLE(0, 5), 0x0504030201); + assert.equal(buf.readUIntBE(0, 5), 0x0102030405); + assert.equal(buf.readUIntLE(0, 6), 0x060504030201); + assert.equal(buf.readUIntBE(0, 6), 0x010203040506); + assert.equal(buf.readIntLE(0, 1), 0x01); + assert.equal(buf.readIntBE(0, 1), 0x01); + assert.equal(buf.readIntLE(0, 3), 0x030201); + assert.equal(buf.readIntBE(0, 3), 0x010203); + assert.equal(buf.readIntLE(0, 5), 0x0504030201); + assert.equal(buf.readIntBE(0, 5), 0x0102030405); + assert.equal(buf.readIntLE(0, 6), 0x060504030201); + assert.equal(buf.readIntBE(0, 6), 0x010203040506); +})(); + +// test for common write(U)IntLE/BE +(function() { + var buf = Buffer.allocUnsafe(3); + buf.writeUIntLE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); + assert.equal(buf.readUIntLE(0, 3), 0x123456); + + buf = Buffer.allocUnsafe(3); + buf.writeUIntBE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); + assert.equal(buf.readUIntBE(0, 3), 0x123456); + + buf = Buffer.allocUnsafe(3); + buf.writeIntLE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); + assert.equal(buf.readIntLE(0, 3), 0x123456); + + buf = Buffer.allocUnsafe(3); + buf.writeIntBE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); + assert.equal(buf.readIntBE(0, 3), 0x123456); + + buf = Buffer.allocUnsafe(3); + buf.writeIntLE(-0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]); + assert.equal(buf.readIntLE(0, 3), -0x123456); + + buf = Buffer.allocUnsafe(3); + buf.writeIntBE(-0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]); + assert.equal(buf.readIntBE(0, 3), -0x123456); + + buf = Buffer.allocUnsafe(3); + buf.writeIntLE(-0x123400, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x00, 0xcc, 0xed]); + assert.equal(buf.readIntLE(0, 3), -0x123400); + + buf = Buffer.allocUnsafe(3); + buf.writeIntBE(-0x123400, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xed, 0xcc, 0x00]); + assert.equal(buf.readIntBE(0, 3), -0x123400); + + buf = Buffer.allocUnsafe(3); + buf.writeIntLE(-0x120000, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0xee]); + assert.equal(buf.readIntLE(0, 3), -0x120000); + + buf = Buffer.allocUnsafe(3); + buf.writeIntBE(-0x120000, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xee, 0x00, 0x00]); + assert.equal(buf.readIntBE(0, 3), -0x120000); + + buf = Buffer.allocUnsafe(5); + buf.writeUIntLE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); + assert.equal(buf.readUIntLE(0, 5), 0x1234567890); + + buf = Buffer.allocUnsafe(5); + buf.writeUIntBE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); + assert.equal(buf.readUIntBE(0, 5), 0x1234567890); + + buf = Buffer.allocUnsafe(5); + buf.writeIntLE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); + assert.equal(buf.readIntLE(0, 5), 0x1234567890); + + buf = Buffer.allocUnsafe(5); + buf.writeIntBE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); + assert.equal(buf.readIntBE(0, 5), 0x1234567890); + + buf = Buffer.allocUnsafe(5); + buf.writeIntLE(-0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]); + assert.equal(buf.readIntLE(0, 5), -0x1234567890); + + buf = Buffer.allocUnsafe(5); + buf.writeIntBE(-0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]); + assert.equal(buf.readIntBE(0, 5), -0x1234567890); + + buf = Buffer.allocUnsafe(5); + buf.writeIntLE(-0x0012000000, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0x00, 0xee, 0xff]); + assert.equal(buf.readIntLE(0, 5), -0x0012000000); + + buf = Buffer.allocUnsafe(5); + buf.writeIntBE(-0x0012000000, 0, 5); + assert.deepEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); + assert.equal(buf.readIntBE(0, 5), -0x0012000000); +})(); + +// test Buffer slice +(function() { + var buf = Buffer.from('0123456789'); + assert.equal(buf.slice(-10, 10), '0123456789'); + assert.equal(buf.slice(-20, 10), '0123456789'); + assert.equal(buf.slice(-20, -10), ''); + assert.equal(buf.slice(), '0123456789'); + assert.equal(buf.slice(0), '0123456789'); + assert.equal(buf.slice(0, 0), ''); + assert.equal(buf.slice(undefined), '0123456789'); + assert.equal(buf.slice('foobar'), '0123456789'); + assert.equal(buf.slice(undefined, undefined), '0123456789'); + + assert.equal(buf.slice(2), '23456789'); + assert.equal(buf.slice(5), '56789'); + assert.equal(buf.slice(10), ''); + assert.equal(buf.slice(5, 8), '567'); + assert.equal(buf.slice(8, -1), '8'); + assert.equal(buf.slice(-10), '0123456789'); + assert.equal(buf.slice(0, -9), '0'); + assert.equal(buf.slice(0, -10), ''); + assert.equal(buf.slice(0, -1), '012345678'); + assert.equal(buf.slice(2, -2), '234567'); + assert.equal(buf.slice(0, 65536), '0123456789'); + assert.equal(buf.slice(65536, 0), ''); + assert.equal(buf.slice(-5, -8), ''); + assert.equal(buf.slice(-5, -3), '56'); + assert.equal(buf.slice(-10, 10), '0123456789'); + for (let i = 0, s = buf.toString(); i < buf.length; ++i) { + assert.equal(buf.slice(i), s.slice(i)); + assert.equal(buf.slice(0, i), s.slice(0, i)); + assert.equal(buf.slice(-i), s.slice(-i)); + assert.equal(buf.slice(0, -i), s.slice(0, -i)); + } + + var utf16Buf = Buffer.from('0123456789', 'utf16le'); + assert.deepEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); + + assert.equal(buf.slice('0', '1'), '0'); + assert.equal(buf.slice('-5', '10'), '56789'); + assert.equal(buf.slice('-10', '10'), '0123456789'); + assert.equal(buf.slice('-10', '-5'), '01234'); + assert.equal(buf.slice('-10', '-0'), ''); + assert.equal(buf.slice('111'), ''); + assert.equal(buf.slice('0', '-111'), ''); + + // try to slice a zero length Buffer + // see https://github.com/joyent/node/issues/5881 + SlowBuffer(0).slice(0, 1); +})(); + +// Regression test for #5482: should throw but not assert in C++ land. +assert.throws(function() { + Buffer.from('', 'buffer'); +}, TypeError); + +// Regression test for #6111. Constructing a buffer from another buffer +// should a) work, and b) not corrupt the source buffer. +(function() { + var a = [0]; + for (let i = 0; i < 7; ++i) a = a.concat(a); + a = a.map(function(_, i) { return i; }); + const b = Buffer.from(a); + const c = Buffer.from(b); + assert.equal(b.length, a.length); + assert.equal(c.length, a.length); + for (let i = 0, k = a.length; i < k; ++i) { + assert.equal(a[i], i); + assert.equal(b[i], i); + assert.equal(c[i], i); + } +})(); + + +assert.throws(function() { + Buffer.allocUnsafe((-1 >>> 0) + 1); +}, RangeError); + +assert.throws(function() { + SlowBuffer((-1 >>> 0) + 1); +}, RangeError); + +if (common.hasCrypto) { + // Test truncation after decode + var crypto = require('crypto'); + + var b1 = Buffer.from('YW55=======', 'base64'); + var b2 = Buffer.from('YW55', 'base64'); + + assert.equal( + crypto.createHash('sha1').update(b1).digest('hex'), + crypto.createHash('sha1').update(b2).digest('hex') + ); +} else { + console.log('1..0 # Skipped: missing crypto'); +} + +// Test Compare +{ + const b = Buffer.alloc(1, 'a'); + const c = Buffer.alloc(1, 'c'); + const d = Buffer.alloc(2, 'aa'); + + assert.equal(b.compare(c), -1); + assert.equal(c.compare(d), 1); + assert.equal(d.compare(b), 1); + assert.equal(b.compare(d), -1); + assert.equal(b.compare(b), 0); + + assert.equal(Buffer.compare(b, c), -1); + assert.equal(Buffer.compare(c, d), 1); + assert.equal(Buffer.compare(d, b), 1); + assert.equal(Buffer.compare(b, d), -1); + assert.equal(Buffer.compare(c, c), 0); + + assert.equal(Buffer.compare(Buffer.alloc(0), Buffer.alloc(0)), 0); + assert.equal(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1)), -1); + assert.equal(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1); +} + +assert.throws(function() { + var b = Buffer.allocUnsafe(1); + Buffer.compare(b, 'abc'); +}); + +assert.throws(function() { + var b = Buffer.allocUnsafe(1); + Buffer.compare('abc', b); +}); + +assert.throws(function() { + var b = Buffer.allocUnsafe(1); + b.compare('abc'); +}); + +// Test Equals +{ + const b = Buffer.alloc(5, 'abcdf'); + const c = Buffer.alloc(5, 'abcdf'); + const d = Buffer.alloc(5, 'abcde'); + const e = Buffer.alloc(6, 'abcdef'); + + assert.ok(b.equals(c)); + assert.ok(!c.equals(d)); + assert.ok(!d.equals(e)); + assert.ok(d.equals(d)); +} + +assert.throws(function() { + var b = Buffer.allocUnsafe(1); + b.equals('abc'); +}); + +// Regression test for https://github.com/nodejs/node/issues/649. +assert.throws(() => { Buffer.allocUnsafe(1422561062959).toString('utf8');}); + +var ps = Buffer.poolSize; +Buffer.poolSize = 0; +assert.equal(Buffer.allocUnsafe(1).parent, undefined); +Buffer.poolSize = ps; + +// Test Buffer.copy() segfault +assert.throws(function() { + Buffer.allocUnsafe(10).copy(); +}); + +const regErrorMsg = new RegExp('First argument must be a string, Buffer, ' + + 'ArrayBuffer, Array, or array-like object.'); + +assert.throws(function() { + Buffer.from(); +}, regErrorMsg); + +assert.throws(function() { + Buffer.from(null); +}, regErrorMsg); + + +// Test prototype getters don't throw +assert.equal(Buffer.prototype.parent, undefined); +assert.equal(Buffer.prototype.offset, undefined); +assert.equal(SlowBuffer.prototype.parent, undefined); +assert.equal(SlowBuffer.prototype.offset, undefined); diff --git a/test/parallel/test-buffer-arraybuffer.js b/test/parallel/test-buffer-arraybuffer.js index 56811a950e63f0..864081e14ddeeb 100644 --- a/test/parallel/test-buffer-arraybuffer.js +++ b/test/parallel/test-buffer-arraybuffer.js @@ -9,7 +9,7 @@ const LENGTH = 16; const ab = new ArrayBuffer(LENGTH); const dv = new DataView(ab); const ui = new Uint8Array(ab); -const buf = new Buffer(ab); +const buf = Buffer.from(ab); assert.ok(buf instanceof Buffer); @@ -42,12 +42,68 @@ assert.throws(function() { function AB() { } Object.setPrototypeOf(AB, ArrayBuffer); Object.setPrototypeOf(AB.prototype, ArrayBuffer.prototype); - new Buffer(new AB()); + Buffer.from(new AB()); }, TypeError); // write{Double,Float}{LE,BE} with noAssert should not crash, cf. #3766 -var b = new Buffer(1); +var b = Buffer.allocUnsafe(1); b.writeFloatLE(11.11, 0, true); b.writeFloatBE(11.11, 0, true); b.writeDoubleLE(11.11, 0, true); b.writeDoubleBE(11.11, 0, true); + +// Test the byteOffset and length arguments +{ + const ab = new Uint8Array(5); + ab[0] = 1; + ab[1] = 2; + ab[2] = 3; + ab[3] = 4; + ab[4] = 5; + const buf = Buffer.from(ab.buffer, 1, 3); + assert.equal(buf.length, 3); + assert.equal(buf[0], 2); + assert.equal(buf[1], 3); + assert.equal(buf[2], 4); + buf[0] = 9; + assert.equal(ab[1], 9); + + assert.throws(() => Buffer.from(ab.buffer, 6), (err) => { + assert(err instanceof RangeError); + assert(/'offset' is out of bounds/.test(err.message)); + return true; + }); + assert.throws(() => Buffer.from(ab.buffer, 3, 6), (err) => { + assert(err instanceof RangeError); + assert(/'length' is out of bounds/.test(err.message)); + return true; + }); +} + +// Test the deprecated Buffer() version also +{ + const ab = new Uint8Array(5); + ab[0] = 1; + ab[1] = 2; + ab[2] = 3; + ab[3] = 4; + ab[4] = 5; + const buf = Buffer(ab.buffer, 1, 3); + assert.equal(buf.length, 3); + assert.equal(buf[0], 2); + assert.equal(buf[1], 3); + assert.equal(buf[2], 4); + buf[0] = 9; + assert.equal(ab[1], 9); + + assert.throws(() => Buffer(ab.buffer, 6), (err) => { + assert(err instanceof RangeError); + assert(/'offset' is out of bounds/.test(err.message)); + return true; + }); + assert.throws(() => Buffer(ab.buffer, 3, 6), (err) => { + assert(err instanceof RangeError); + assert(/'length' is out of bounds/.test(err.message)); + return true; + }); +} diff --git a/test/parallel/test-buffer-ascii.js b/test/parallel/test-buffer-ascii.js index 94ba85a22761dd..74522f34fa2aa1 100644 --- a/test/parallel/test-buffer-ascii.js +++ b/test/parallel/test-buffer-ascii.js @@ -4,7 +4,7 @@ var assert = require('assert'); // ASCII conversion in node.js simply masks off the high bits, // it doesn't do transliteration. -assert.equal(Buffer('hérité').toString('ascii'), 'hC)ritC)'); +assert.equal(Buffer.from('hérité').toString('ascii'), 'hC)ritC)'); // 71 characters, 78 bytes. The ’ character is a triple-byte sequence. var input = 'C’est, graphiquement, la réunion d’un accent aigu ' + @@ -14,7 +14,7 @@ var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' + 'accent grave.'; -var buf = Buffer(input); +var buf = Buffer.from(input); for (var i = 0; i < expected.length; ++i) { assert.equal(buf.slice(i).toString('ascii'), expected.slice(i)); diff --git a/test/parallel/test-buffer-bytelength.js b/test/parallel/test-buffer-bytelength.js index ef68097157b1d8..aaffc36bd2eff1 100644 --- a/test/parallel/test-buffer-bytelength.js +++ b/test/parallel/test-buffer-bytelength.js @@ -11,9 +11,9 @@ assert.equal(Buffer.byteLength({}, 'binary'), 15); assert.equal(Buffer.byteLength(), 9); // buffer -var incomplete = new Buffer([0xe4, 0xb8, 0xad, 0xe6, 0x96]); +var incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]); assert.equal(Buffer.byteLength(incomplete), 5); -var ascii = new Buffer('abc'); +var ascii = Buffer.from('abc'); assert.equal(Buffer.byteLength(ascii), 3); // special case: zero length string diff --git a/test/parallel/test-buffer-concat.js b/test/parallel/test-buffer-concat.js index 7aec8117204b62..bc628e656b4f11 100644 --- a/test/parallel/test-buffer-concat.js +++ b/test/parallel/test-buffer-concat.js @@ -3,9 +3,9 @@ require('../common'); var assert = require('assert'); var zero = []; -var one = [ new Buffer('asdf') ]; +var one = [ Buffer.from('asdf') ]; var long = []; -for (var i = 0; i < 10; i++) long.push(new Buffer('asdf')); +for (var i = 0; i < 10; i++) long.push(Buffer.from('asdf')); var flatZero = Buffer.concat(zero); var flatOne = Buffer.concat(one); @@ -22,10 +22,10 @@ assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf'))); assertWrongList(); assertWrongList(null); -assertWrongList(new Buffer('hello')); +assertWrongList(Buffer.from('hello')); assertWrongList([42]); assertWrongList(['hello', 'world']); -assertWrongList(['hello', new Buffer('world')]); +assertWrongList(['hello', Buffer.from('world')]); function assertWrongList(value) { assert.throws(function() { diff --git a/test/parallel/test-buffer-fakes.js b/test/parallel/test-buffer-fakes.js index ca268fa265fb0b..758ebbf0053732 100644 --- a/test/parallel/test-buffer-fakes.js +++ b/test/parallel/test-buffer-fakes.js @@ -11,7 +11,7 @@ Object.setPrototypeOf(FakeBuffer.prototype, Buffer.prototype); const fb = new FakeBuffer(); assert.throws(function() { - new Buffer(fb); + Buffer.from(fb); }, TypeError); assert.throws(function() { @@ -19,7 +19,7 @@ assert.throws(function() { }, TypeError); assert.throws(function() { - Buffer.compare(fb, new Buffer(0)); + Buffer.compare(fb, Buffer.alloc(0)); }, TypeError); assert.throws(function() { @@ -35,7 +35,7 @@ assert.throws(function() { }, TypeError); assert.throws(function() { - fb.equals(new Buffer(0)); + fb.equals(Buffer.alloc(0)); }, TypeError); assert.throws(function() { diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index 4ff0b12a46c227..456e60df7609b3 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -5,8 +5,8 @@ const assert = require('assert'); const os = require('os'); const SIZE = 28; -const buf1 = Buffer(SIZE); -const buf2 = Buffer(SIZE); +const buf1 = Buffer.allocUnsafe(SIZE); +const buf2 = Buffer.allocUnsafe(SIZE); // Default encoding @@ -49,7 +49,7 @@ testBufs('\u0222aa', 8, 1, 'utf8'); testBufs('a\u0234b\u0235c\u0236', 4, -1, 'utf8'); testBufs('a\u0234b\u0235c\u0236', 4, 1, 'utf8'); testBufs('a\u0234b\u0235c\u0236', 12, 1, 'utf8'); -assert.equal(Buffer(1).fill(0).fill('\u0222')[0], 0xc8); +assert.equal(Buffer.allocUnsafe(1).fill(0).fill('\u0222')[0], 0xc8); // BINARY @@ -91,7 +91,7 @@ testBufs('\u0222aa', 8, 1, 'ucs2'); testBufs('a\u0234b\u0235c\u0236', 4, -1, 'ucs2'); testBufs('a\u0234b\u0235c\u0236', 4, 1, 'ucs2'); testBufs('a\u0234b\u0235c\u0236', 12, 1, 'ucs2'); -assert.equal(Buffer(1).fill('\u0222', 'ucs2')[0], +assert.equal(Buffer.allocUnsafe(1).fill('\u0222', 'ucs2')[0], os.endianness() === 'LE' ? 0x22 : 0x02); @@ -140,13 +140,13 @@ testBufs('Yci0Ysi1Y8i2', 12, 1, 'ucs2'); // Buffer -const buf2Fill = Buffer(1).fill(2); +const buf2Fill = Buffer.allocUnsafe(1).fill(2); assert.deepEqual(genBuffer(4, [buf2Fill]), [2, 2, 2, 2]); assert.deepEqual(genBuffer(4, [buf2Fill, 1]), [0, 2, 2, 2]); assert.deepEqual(genBuffer(4, [buf2Fill, 1, 3]), [0, 2, 2, 0]); assert.deepEqual(genBuffer(4, [buf2Fill, 1, 1]), [0, 0, 0, 0]); assert.deepEqual(genBuffer(4, [buf2Fill, 1, -1]), [0, 0, 0, 0]); -const hexBufFill = Buffer(2).fill(0).fill('0102', 'hex'); +const hexBufFill = Buffer.allocUnsafe(2).fill(0).fill('0102', 'hex'); assert.deepEqual(genBuffer(4, [hexBufFill]), [1, 2, 1, 2]); assert.deepEqual(genBuffer(4, [hexBufFill, 1]), [0, 1, 2, 1]); assert.deepEqual(genBuffer(4, [hexBufFill, 1, 3]), [0, 1, 2, 0]); @@ -166,7 +166,7 @@ assert.throws(() => buf1.fill('a', 0, 0, 'foo')); function genBuffer(size, args) { - const b = Buffer(size); + const b = Buffer.allocUnsafe(size); return b.fill(0).fill.apply(b, args); } diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 907bbdf961efd8..2d46e1b6e6f6d3 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -4,12 +4,12 @@ const assert = require('assert'); const Buffer = require('buffer').Buffer; -const b = new Buffer('abcdef'); -const buf_a = new Buffer('a'); -const buf_bc = new Buffer('bc'); -const buf_f = new Buffer('f'); -const buf_z = new Buffer('z'); -const buf_empty = new Buffer(''); +const b = Buffer.from('abcdef'); +const buf_a = Buffer.from('a'); +const buf_bc = Buffer.from('bc'); +const buf_f = Buffer.from('f'); +const buf_z = Buffer.from('z'); +const buf_empty = Buffer.from(''); assert(b.includes('a')); assert(!b.includes('a', 1)); @@ -71,70 +71,72 @@ assert(b.includes('f', 5)); assert(b.includes('f', -1)); assert(!b.includes('f', 6)); -assert(b.includes(Buffer('d'), 2)); -assert(b.includes(Buffer('f'), 5)); -assert(b.includes(Buffer('f'), -1)); -assert(!b.includes(Buffer('f'), 6)); +assert(b.includes(Buffer.from('d'), 2)); +assert(b.includes(Buffer.from('f'), 5)); +assert(b.includes(Buffer.from('f'), -1)); +assert(!b.includes(Buffer.from('f'), 6)); -assert(!Buffer('ff').includes(Buffer('f'), 1, 'ucs2')); +assert(!Buffer.from('ff').includes(Buffer.from('f'), 1, 'ucs2')); // test hex encoding assert( - Buffer(b.toString('hex'), 'hex') + Buffer.from(b.toString('hex'), 'hex') .includes('64', 0, 'hex')); assert( - Buffer(b.toString('hex'), 'hex') - .includes(Buffer('64', 'hex'), 0, 'hex')); + Buffer.from(b.toString('hex'), 'hex') + .includes(Buffer.from('64', 'hex'), 0, 'hex')); // test base64 encoding assert( - Buffer(b.toString('base64'), 'base64') + Buffer.from(b.toString('base64'), 'base64') .includes('ZA==', 0, 'base64')); assert( - Buffer(b.toString('base64'), 'base64') - .includes(Buffer('ZA==', 'base64'), 0, 'base64')); + Buffer.from(b.toString('base64'), 'base64') + .includes(Buffer.from('ZA==', 'base64'), 0, 'base64')); // test ascii encoding assert( - Buffer(b.toString('ascii'), 'ascii') + Buffer.from(b.toString('ascii'), 'ascii') .includes('d', 0, 'ascii')); assert( - Buffer(b.toString('ascii'), 'ascii') - .includes(Buffer('d', 'ascii'), 0, 'ascii')); + Buffer.from(b.toString('ascii'), 'ascii') + .includes(Buffer.from('d', 'ascii'), 0, 'ascii')); // test binary encoding assert( - Buffer(b.toString('binary'), 'binary') + Buffer.from(b.toString('binary'), 'binary') .includes('d', 0, 'binary')); assert( - Buffer(b.toString('binary'), 'binary') - .includes(Buffer('d', 'binary'), 0, 'binary')); + Buffer.from(b.toString('binary'), 'binary') + .includes(Buffer.from('d', 'binary'), 0, 'binary')); // test usc2 encoding -var twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); +var twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); assert(twoByteString.includes('\u0395', 4, 'ucs2')); assert(twoByteString.includes('\u03a3', -4, 'ucs2')); assert(twoByteString.includes('\u03a3', -6, 'ucs2')); assert(twoByteString.includes( - new Buffer('\u03a3', 'ucs2'), -6, 'ucs2')); + Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2')); assert(!twoByteString.includes('\u03a3', -2, 'ucs2')); const mixedByteStringUcs2 = - new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); + Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); assert(mixedByteStringUcs2.includes('bc', 0, 'ucs2')); assert(mixedByteStringUcs2.includes('\u03a3', 0, 'ucs2')); assert(!mixedByteStringUcs2.includes('\u0396', 0, 'ucs2')); assert( - 6, mixedByteStringUcs2.includes(new Buffer('bc', 'ucs2'), 0, 'ucs2')); + 6, mixedByteStringUcs2.includes(Buffer.from('bc', 'ucs2'), 0, 'ucs2')); assert( - 10, mixedByteStringUcs2.includes(new Buffer('\u03a3', 'ucs2'), 0, 'ucs2')); + 10, mixedByteStringUcs2.includes(Buffer.from('\u03a3', 'ucs2'), + 0, 'ucs2')); assert( - -1, mixedByteStringUcs2.includes(new Buffer('\u0396', 'ucs2'), 0, 'ucs2')); + -1, mixedByteStringUcs2.includes(Buffer.from('\u0396', 'ucs2'), + 0, 'ucs2')); -twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); +twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); // Test single char pattern assert(twoByteString.includes('\u039a', 0, 'ucs2')); @@ -150,7 +152,7 @@ assert(twoByteString.includes('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma'); assert(twoByteString.includes('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma'); assert(twoByteString.includes('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); -const mixedByteStringUtf8 = new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395'); +const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); assert(mixedByteStringUtf8.includes('bc')); assert(mixedByteStringUtf8.includes('bc', 5)); assert(mixedByteStringUtf8.includes('bc', -8)); @@ -165,7 +167,7 @@ for (let i = 66; i < 76; i++) { // from 'B' to 'K' longString = longString + String.fromCharCode(i) + longString; } -const longBufferString = new Buffer(longString); +const longBufferString = Buffer.from(longString); // pattern of 15 chars, repeated every 16 chars in long var pattern = 'ABACABADABACABA'; @@ -181,7 +183,7 @@ assert(longBufferString.includes(pattern), 'Long JABACABA..., First J'); assert(longBufferString.includes(pattern, 512), 'Long JABACABA..., Second J'); // Search for a non-ASCII string in a pure ASCII string. -const asciiString = new Buffer( +const asciiString = Buffer.from( 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); assert(!asciiString.includes('\x2061')); assert(asciiString.includes('leb', 0)); @@ -190,8 +192,8 @@ assert(asciiString.includes('leb', 0)); const allCodePoints = []; for (let i = 0; i < 65536; i++) allCodePoints[i] = i; const allCharsString = String.fromCharCode.apply(String, allCodePoints); -const allCharsBufferUtf8 = new Buffer(allCharsString); -const allCharsBufferUcs2 = new Buffer(allCharsString, 'ucs2'); +const allCharsBufferUtf8 = Buffer.from(allCharsString); +const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2'); // Search for string long enough to trigger complex search with ASCII pattern // and UC16 subject. diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 101a60cbe5ae7f..7fb862d9190d89 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -4,12 +4,12 @@ var assert = require('assert'); var Buffer = require('buffer').Buffer; -var b = new Buffer('abcdef'); -var buf_a = new Buffer('a'); -var buf_bc = new Buffer('bc'); -var buf_f = new Buffer('f'); -var buf_z = new Buffer('z'); -var buf_empty = new Buffer(''); +var b = Buffer.from('abcdef'); +var buf_a = Buffer.from('a'); +var buf_bc = Buffer.from('bc'); +var buf_f = Buffer.from('f'); +var buf_z = Buffer.from('z'); +var buf_empty = Buffer.from(''); assert.equal(b.indexOf('a'), 0); assert.equal(b.indexOf('a', 1), -1); @@ -71,86 +71,86 @@ assert.equal(b.indexOf('f', 5), 5); assert.equal(b.indexOf('f', -1), 5); assert.equal(b.indexOf('f', 6), -1); -assert.equal(b.indexOf(Buffer('d'), 2), 3); -assert.equal(b.indexOf(Buffer('f'), 5), 5); -assert.equal(b.indexOf(Buffer('f'), -1), 5); -assert.equal(b.indexOf(Buffer('f'), 6), -1); +assert.equal(b.indexOf(Buffer.from('d'), 2), 3); +assert.equal(b.indexOf(Buffer.from('f'), 5), 5); +assert.equal(b.indexOf(Buffer.from('f'), -1), 5); +assert.equal(b.indexOf(Buffer.from('f'), 6), -1); -assert.equal(Buffer('ff').indexOf(Buffer('f'), 1, 'ucs2'), -1); +assert.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1); // test hex encoding assert.equal( - Buffer(b.toString('hex'), 'hex') + Buffer.from(b.toString('hex'), 'hex') .indexOf('64', 0, 'hex'), 3); assert.equal( - Buffer(b.toString('hex'), 'hex') - .indexOf(Buffer('64', 'hex'), 0, 'hex'), 3); + Buffer.from(b.toString('hex'), 'hex') + .indexOf(Buffer.from('64', 'hex'), 0, 'hex'), 3); // test base64 encoding assert.equal( - Buffer(b.toString('base64'), 'base64') + Buffer.from(b.toString('base64'), 'base64') .indexOf('ZA==', 0, 'base64'), 3); assert.equal( - Buffer(b.toString('base64'), 'base64') - .indexOf(Buffer('ZA==', 'base64'), 0, 'base64'), 3); + Buffer.from(b.toString('base64'), 'base64') + .indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'), 3); // test ascii encoding assert.equal( - Buffer(b.toString('ascii'), 'ascii') + Buffer.from(b.toString('ascii'), 'ascii') .indexOf('d', 0, 'ascii'), 3); assert.equal( - Buffer(b.toString('ascii'), 'ascii') - .indexOf(Buffer('d', 'ascii'), 0, 'ascii'), 3); + Buffer.from(b.toString('ascii'), 'ascii') + .indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'), 3); // test binary encoding assert.equal( - Buffer(b.toString('binary'), 'binary') + Buffer.from(b.toString('binary'), 'binary') .indexOf('d', 0, 'binary'), 3); assert.equal( - Buffer(b.toString('binary'), 'binary') - .indexOf(Buffer('d', 'binary'), 0, 'binary'), 3); + Buffer.from(b.toString('binary'), 'binary') + .indexOf(Buffer.from('d', 'binary'), 0, 'binary'), 3); assert.equal( - Buffer('aa\u00e8aa', 'binary') + Buffer.from('aa\u00e8aa', 'binary') .indexOf('\u00e8', 'binary'), 2); assert.equal( - Buffer('\u00e8', 'binary') + Buffer.from('\u00e8', 'binary') .indexOf('\u00e8', 'binary'), 0); assert.equal( - Buffer('\u00e8', 'binary') - .indexOf(Buffer('\u00e8', 'binary'), 'binary'), 0); + Buffer.from('\u00e8', 'binary') + .indexOf(Buffer.from('\u00e8', 'binary'), 'binary'), 0); // test optional offset with passed encoding -assert.equal(new Buffer('aaaa0').indexOf('30', 'hex'), 4); -assert.equal(new Buffer('aaaa00a').indexOf('3030', 'hex'), 4); +assert.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4); +assert.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4); { // test usc2 encoding - const twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); + const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); assert.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')); assert.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')); assert.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')); assert.equal(4, twoByteString.indexOf( - new Buffer('\u03a3', 'ucs2'), -6, 'ucs2')); + Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2')); assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); } var mixedByteStringUcs2 = - new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); + Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')); assert.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')); assert.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')); assert.equal( - 6, mixedByteStringUcs2.indexOf(new Buffer('bc', 'ucs2'), 0, 'ucs2')); + 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2')); assert.equal( - 10, mixedByteStringUcs2.indexOf(new Buffer('\u03a3', 'ucs2'), 0, 'ucs2')); + 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')); assert.equal( - -1, mixedByteStringUcs2.indexOf(new Buffer('\u0396', 'ucs2'), 0, 'ucs2')); + -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')); { - const twoByteString = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); + const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); // Test single char pattern assert.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2')); @@ -171,7 +171,7 @@ assert.equal( 6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); } -var mixedByteStringUtf8 = new Buffer('\u039a\u0391abc\u03a3\u03a3\u0395'); +var mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); assert.equal(5, mixedByteStringUtf8.indexOf('bc')); assert.equal(5, mixedByteStringUtf8.indexOf('bc', 5)); assert.equal(5, mixedByteStringUtf8.indexOf('bc', -8)); @@ -186,7 +186,7 @@ for (let i = 66; i < 76; i++) { // from 'B' to 'K' longString = longString + String.fromCharCode(i) + longString; } -var longBufferString = new Buffer(longString); +var longBufferString = Buffer.from(longString); // pattern of 15 chars, repeated every 16 chars in long var pattern = 'ABACABADABACABA'; @@ -205,7 +205,7 @@ assert.equal( 1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J'); // Search for a non-ASCII string in a pure ASCII string. -var asciiString = new Buffer( +var asciiString = Buffer.from( 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); assert.equal(-1, asciiString.indexOf('\x2061')); assert.equal(3, asciiString.indexOf('leb', 0)); @@ -214,8 +214,8 @@ assert.equal(3, asciiString.indexOf('leb', 0)); var allCodePoints = []; for (let i = 0; i < 65536; i++) allCodePoints[i] = i; var allCharsString = String.fromCharCode.apply(String, allCodePoints); -var allCharsBufferUtf8 = new Buffer(allCharsString); -var allCharsBufferUcs2 = new Buffer(allCharsString, 'ucs2'); +var allCharsBufferUtf8 = Buffer.from(allCharsString); +var allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2'); // Search for string long enough to trigger complex search with ASCII pattern // and UC16 subject. diff --git a/test/parallel/test-buffer-inspect.js b/test/parallel/test-buffer-inspect.js index 6d44389de735a2..fdff73615293b9 100644 --- a/test/parallel/test-buffer-inspect.js +++ b/test/parallel/test-buffer-inspect.js @@ -8,10 +8,10 @@ var buffer = require('buffer'); buffer.INSPECT_MAX_BYTES = 2; -var b = new Buffer(4); +var b = Buffer.allocUnsafe(4); b.fill('1234'); -var s = new buffer.SlowBuffer(4); +var s = buffer.SlowBuffer(4); s.fill('1234'); var expected = ''; @@ -19,10 +19,10 @@ var expected = ''; assert.strictEqual(util.inspect(b), expected); assert.strictEqual(util.inspect(s), expected); -b = new Buffer(2); +b = Buffer.allocUnsafe(2); b.fill('12'); -s = new buffer.SlowBuffer(2); +s = buffer.SlowBuffer(2); s.fill('12'); expected = ''; diff --git a/test/parallel/test-buffer-iterator.js b/test/parallel/test-buffer-iterator.js index 06bf826a91e26c..d8525dbf05353e 100644 --- a/test/parallel/test-buffer-iterator.js +++ b/test/parallel/test-buffer-iterator.js @@ -2,7 +2,7 @@ require('../common'); var assert = require('assert'); -var buffer = new Buffer([1, 2, 3, 4, 5]); +var buffer = Buffer.from([1, 2, 3, 4, 5]); var arr; var b; diff --git a/test/parallel/test-buffer-safe-unsafe.js b/test/parallel/test-buffer-safe-unsafe.js new file mode 100644 index 00000000000000..6646f760564432 --- /dev/null +++ b/test/parallel/test-buffer-safe-unsafe.js @@ -0,0 +1,14 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); + +const safe = Buffer.alloc(10); + +function isZeroFilled(buf) { + for (let n = 0; n < buf.length; n++) + if (buf[n] > 0) return false; + return true; +} + +assert(isZeroFilled(safe)); diff --git a/test/parallel/test-buffer-slow.js b/test/parallel/test-buffer-slow.js index 92aa7c3d045315..c5399514d9b798 100644 --- a/test/parallel/test-buffer-slow.js +++ b/test/parallel/test-buffer-slow.js @@ -9,7 +9,7 @@ const SlowBuffer = buffer.SlowBuffer; const ones = [1, 1, 1, 1]; // should create a Buffer -let sb = new SlowBuffer(4); +let sb = SlowBuffer(4); assert(sb instanceof Buffer); assert.strictEqual(sb.length, 4); sb.fill(1); @@ -28,7 +28,8 @@ assert.deepEqual(sb, ones); // should work with edge cases assert.strictEqual(SlowBuffer(0).length, 0); try { - assert.strictEqual(SlowBuffer(buffer.kMaxLength).length, buffer.kMaxLength); + assert.strictEqual( + SlowBuffer(buffer.kMaxLength).length, buffer.kMaxLength); } catch (e) { assert.equal(e.message, 'Array buffer allocation failed'); } @@ -45,11 +46,11 @@ assert.strictEqual(SlowBuffer('string').length, 0); // should throw with invalid length assert.throws(function() { - new SlowBuffer(Infinity); + SlowBuffer(Infinity); }, 'invalid Buffer length'); assert.throws(function() { - new SlowBuffer(-1); + SlowBuffer(-1); }, 'invalid Buffer length'); assert.throws(function() { - new SlowBuffer(buffer.kMaxLength + 1); + SlowBuffer(buffer.kMaxLength + 1); }, 'invalid Buffer length'); diff --git a/test/parallel/test-buffer-zero-fill-cli.js b/test/parallel/test-buffer-zero-fill-cli.js new file mode 100644 index 00000000000000..91679498a1a560 --- /dev/null +++ b/test/parallel/test-buffer-zero-fill-cli.js @@ -0,0 +1,32 @@ +'use strict'; +// Flags: --zero-fill-buffers + +// when using --zero-fill-buffers, every Buffer and SlowBuffer +// instance must be zero filled upon creation + +require('../common'); +const SlowBuffer = require('buffer').SlowBuffer; +const assert = require('assert'); + +function isZeroFilled(buf) { + for (let n = 0; n < buf.length; n++) + if (buf[n] > 0) return false; + return true; +} + +// This can be somewhat unreliable because the +// allocated memory might just already happen to +// contain all zeroes. The test is run multiple +// times to improve the reliability. +for (let i = 0; i < 50; i++) { + const bufs = [ + Buffer.alloc(20), + Buffer.allocUnsafe(20), + SlowBuffer(20), + Buffer(20), + new SlowBuffer(20) + ]; + for (const buf of bufs) { + assert(isZeroFilled(buf)); + } +} diff --git a/test/parallel/test-buffer-zero-fill-reset.js b/test/parallel/test-buffer-zero-fill-reset.js index 56fb77818a1284..3076b25ce637fc 100644 --- a/test/parallel/test-buffer-zero-fill-reset.js +++ b/test/parallel/test-buffer-zero-fill-reset.js @@ -13,7 +13,7 @@ function testUint8Array(ui) { for (let i = 0; i < 100; i++) { - new Buffer(0); + Buffer.alloc(0); const ui = new Uint8Array(65); assert.ok(testUint8Array(ui), 'Uint8Array is not zero-filled'); } diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 8d42bea82d5e8c..b4b1d4356c4e81 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -24,7 +24,7 @@ for (let i = 0; i < 1024; i++) { assert.strictEqual(i % 256, b[i]); } -var c = new Buffer(512); +var c = Buffer(512); console.log('c.length == %d', c.length); assert.strictEqual(512, c.length); @@ -177,7 +177,7 @@ Buffer(8).fill(''); } // copy string longer than buffer length (failure will segfault) -var bb = new Buffer(10); +var bb = Buffer(10); bb.fill('hello crazy world'); @@ -236,7 +236,7 @@ assert.strictEqual('Unknown encoding: invalid', caught_error.message); new Buffer(''); new Buffer('', 'ascii'); new Buffer('', 'binary'); -new Buffer(0); +Buffer(0); // try to write a 0-length string beyond the end of b assert.throws(function() { @@ -259,14 +259,14 @@ assert.throws(function() { }, RangeError); // try to copy 0 bytes worth of data into an empty buffer -b.copy(new Buffer(0), 0, 0, 0); +b.copy(Buffer(0), 0, 0, 0); // try to copy 0 bytes past the end of the target buffer -b.copy(new Buffer(0), 1, 1, 1); -b.copy(new Buffer(1), 1, 1, 1); +b.copy(Buffer(0), 1, 1, 1); +b.copy(Buffer(1), 1, 1, 1); // try to copy 0 bytes from past the end of the source buffer -b.copy(new Buffer(1), 0, 2048, 2048); +b.copy(Buffer(1), 0, 2048, 2048); const rangeBuffer = new Buffer('abc'); @@ -750,7 +750,7 @@ for (let i = 0; i < 256; i++) { function buildBuffer(data) { if (Array.isArray(data)) { - var buffer = new Buffer(data.length); + var buffer = Buffer(data.length); data.forEach(function(v, k) { buffer[k] = v; }); @@ -1035,53 +1035,53 @@ Buffer(Buffer(0), 0, 0); // issue GH-4331 assert.throws(function() { - new Buffer(0xFFFFFFFF); + Buffer(0xFFFFFFFF); }, RangeError); assert.throws(function() { - new Buffer(0xFFFFFFFFF); + Buffer(0xFFFFFFFFF); }, RangeError); // attempt to overflow buffers, similar to previous bug in array buffers assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.readFloatLE(0xffffffff); }, RangeError); assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.writeFloatLE(0.0, 0xffffffff); }, RangeError); assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.readFloatLE(0xffffffff); }, RangeError); assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.writeFloatLE(0.0, 0xffffffff); }, RangeError); // ensure negative values can't get past offset assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.readFloatLE(-1); }, RangeError); assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.writeFloatLE(0.0, -1); }, RangeError); assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.readFloatLE(-1); }, RangeError); assert.throws(function() { - var buf = new Buffer(8); + var buf = Buffer(8); buf.writeFloatLE(0.0, -1); }, RangeError); @@ -1160,92 +1160,92 @@ assert.throws(function() { // test for common write(U)IntLE/BE (function() { - var buf = new Buffer(3); + var buf = Buffer(3); buf.writeUIntLE(0x123456, 0, 3); assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.equal(buf.readUIntLE(0, 3), 0x123456); - buf = new Buffer(3); + buf = Buffer(3); buf.writeUIntBE(0x123456, 0, 3); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); assert.equal(buf.readUIntBE(0, 3), 0x123456); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntLE(0x123456, 0, 3); assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.equal(buf.readIntLE(0, 3), 0x123456); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntBE(0x123456, 0, 3); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); assert.equal(buf.readIntBE(0, 3), 0x123456); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntLE(-0x123456, 0, 3); assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]); assert.equal(buf.readIntLE(0, 3), -0x123456); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntBE(-0x123456, 0, 3); assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]); assert.equal(buf.readIntBE(0, 3), -0x123456); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntLE(-0x123400, 0, 3); assert.deepEqual(buf.toJSON().data, [0x00, 0xcc, 0xed]); assert.equal(buf.readIntLE(0, 3), -0x123400); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntBE(-0x123400, 0, 3); assert.deepEqual(buf.toJSON().data, [0xed, 0xcc, 0x00]); assert.equal(buf.readIntBE(0, 3), -0x123400); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntLE(-0x120000, 0, 3); assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0xee]); assert.equal(buf.readIntLE(0, 3), -0x120000); - buf = new Buffer(3); + buf = Buffer(3); buf.writeIntBE(-0x120000, 0, 3); assert.deepEqual(buf.toJSON().data, [0xee, 0x00, 0x00]); assert.equal(buf.readIntBE(0, 3), -0x120000); - buf = new Buffer(5); + buf = Buffer(5); buf.writeUIntLE(0x1234567890, 0, 5); assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); assert.equal(buf.readUIntLE(0, 5), 0x1234567890); - buf = new Buffer(5); + buf = Buffer(5); buf.writeUIntBE(0x1234567890, 0, 5); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); assert.equal(buf.readUIntBE(0, 5), 0x1234567890); - buf = new Buffer(5); + buf = Buffer(5); buf.writeIntLE(0x1234567890, 0, 5); assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); assert.equal(buf.readIntLE(0, 5), 0x1234567890); - buf = new Buffer(5); + buf = Buffer(5); buf.writeIntBE(0x1234567890, 0, 5); assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); assert.equal(buf.readIntBE(0, 5), 0x1234567890); - buf = new Buffer(5); + buf = Buffer(5); buf.writeIntLE(-0x1234567890, 0, 5); assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]); assert.equal(buf.readIntLE(0, 5), -0x1234567890); - buf = new Buffer(5); + buf = Buffer(5); buf.writeIntBE(-0x1234567890, 0, 5); assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]); assert.equal(buf.readIntBE(0, 5), -0x1234567890); - buf = new Buffer(5); + buf = Buffer(5); buf.writeIntLE(-0x0012000000, 0, 5); assert.deepEqual(buf.toJSON().data, [0x00, 0x00, 0x00, 0xee, 0xff]); assert.equal(buf.readIntLE(0, 5), -0x0012000000); - buf = new Buffer(5); + buf = Buffer(5); buf.writeIntBE(-0x0012000000, 0, 5); assert.deepEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.equal(buf.readIntBE(0, 5), -0x0012000000); @@ -1330,7 +1330,7 @@ assert.throws(function() { }, RangeError); assert.throws(function() { - new SlowBuffer((-1 >>> 0) + 1); + SlowBuffer((-1 >>> 0) + 1); }, RangeError); if (common.hasCrypto) { @@ -1372,17 +1372,17 @@ if (common.hasCrypto) { } assert.throws(function() { - var b = new Buffer(1); + var b = Buffer(1); Buffer.compare(b, 'abc'); }); assert.throws(function() { - var b = new Buffer(1); + var b = Buffer(1); Buffer.compare('abc', b); }); assert.throws(function() { - var b = new Buffer(1); + var b = Buffer(1); b.compare('abc'); }); @@ -1400,7 +1400,7 @@ assert.throws(function() { } assert.throws(function() { - var b = new Buffer(1); + var b = Buffer(1); b.equals('abc'); }); @@ -1417,13 +1417,16 @@ assert.throws(function() { Buffer(10).copy(); }); +const regErrorMsg = new RegExp('First argument must be a string, Buffer, ' + + 'ArrayBuffer, Array, or array-like object.'); + assert.throws(function() { new Buffer(); -}, /Must start with number, buffer, array or string/); +}, regErrorMsg); assert.throws(function() { new Buffer(null); -}, /Must start with number, buffer, array or string/); +}, regErrorMsg); // Test prototype getters don't throw diff --git a/test/parallel/test-child-process-fork-dgram.js b/test/parallel/test-child-process-fork-dgram.js index b4904c51b1714f..f440d9b197ee60 100644 --- a/test/parallel/test-child-process-fork-dgram.js +++ b/test/parallel/test-child-process-fork-dgram.js @@ -45,7 +45,7 @@ if (process.argv[2] === 'child') { var client = dgram.createSocket('udp4'); var child = fork(__filename, ['child']); - var msg = new Buffer('Some bytes'); + var msg = Buffer.from('Some bytes'); var childGotMessage = false; var parentGotMessage = false; diff --git a/test/parallel/test-child-process-spawnsync-input.js b/test/parallel/test-child-process-spawnsync-input.js index 0116f092920a8b..c8c63e4f93092a 100644 --- a/test/parallel/test-child-process-spawnsync-input.js +++ b/test/parallel/test-child-process-spawnsync-input.js @@ -9,8 +9,8 @@ const msgOut = 'this is stdout'; const msgErr = 'this is stderr'; // this is actually not os.EOL? -const msgOutBuf = new Buffer(msgOut + '\n'); -const msgErrBuf = new Buffer(msgErr + '\n'); +const msgOutBuf = Buffer.from(msgOut + '\n'); +const msgErrBuf = Buffer.from(msgErr + '\n'); const args = [ '-e', @@ -71,14 +71,14 @@ assert.strictEqual(ret.stdout.toString('utf8'), options.input); assert.strictEqual(ret.stderr.toString('utf8'), ''); options = { - input: new Buffer('hello world') + input: Buffer.from('hello world') }; ret = spawnSync('cat', [], options); checkSpawnSyncRet(ret); assert.deepEqual(ret.stdout, options.input); -assert.deepEqual(ret.stderr, new Buffer('')); +assert.deepEqual(ret.stderr, Buffer.from('')); verifyBufOutput(spawnSync(process.execPath, args)); diff --git a/test/parallel/test-child-process-spawnsync-maxbuf.js b/test/parallel/test-child-process-spawnsync-maxbuf.js index d8f286d7e01626..317c0fe0ba29a7 100644 --- a/test/parallel/test-child-process-spawnsync-maxbuf.js +++ b/test/parallel/test-child-process-spawnsync-maxbuf.js @@ -7,7 +7,7 @@ const spawnSync = require('child_process').spawnSync; const msgOut = 'this is stdout'; // This is actually not os.EOL? -const msgOutBuf = new Buffer(msgOut + '\n'); +const msgOutBuf = Buffer.from(msgOut + '\n'); const args = [ '-e', diff --git a/test/parallel/test-child-process-stdio-big-write-end.js b/test/parallel/test-child-process-stdio-big-write-end.js index 6a55c2b658e602..8a5afafdcd49e6 100644 --- a/test/parallel/test-child-process-stdio-big-write-end.js +++ b/test/parallel/test-child-process-stdio-big-write-end.js @@ -29,15 +29,13 @@ function parent() { // Write until the buffer fills up. do { - var buf = new Buffer(BUFSIZE); - buf.fill('.'); + var buf = Buffer.alloc(BUFSIZE, '.'); sent += BUFSIZE; } while (child.stdin.write(buf)); // then write a bunch more times. for (var i = 0; i < 100; i++) { - const buf = new Buffer(BUFSIZE); - buf.fill('.'); + const buf = Buffer.alloc(BUFSIZE, '.'); sent += BUFSIZE; child.stdin.write(buf); } diff --git a/test/parallel/test-cluster-dgram-1.js b/test/parallel/test-cluster-dgram-1.js index 9404c55f2bb547..de9c1ef3927c9f 100644 --- a/test/parallel/test-cluster-dgram-1.js +++ b/test/parallel/test-cluster-dgram-1.js @@ -33,7 +33,7 @@ function master() { return; // Start sending messages. - var buf = new Buffer('hello world'); + var buf = Buffer.from('hello world'); var socket = dgram.createSocket('udp4'); var sent = 0; doSend(); diff --git a/test/parallel/test-cluster-dgram-2.js b/test/parallel/test-cluster-dgram-2.js index 69e9e9d7500f59..6825817f588ce9 100644 --- a/test/parallel/test-cluster-dgram-2.js +++ b/test/parallel/test-cluster-dgram-2.js @@ -51,7 +51,7 @@ function master() { function worker() { // Create udp socket and send packets to master. var socket = dgram.createSocket('udp4'); - var buf = new Buffer('hello world'); + var buf = Buffer.from('hello world'); // This test is intended to exercise the cluster binding of udp sockets, but // since sockets aren't clustered when implicitly bound by at first call of diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index fa9a78c26e5b59..b08fb7e0198640 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -62,9 +62,9 @@ for (var i in TEST_CASES) { (function() { var encrypt = crypto.createCipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); if (test.aad) - encrypt.setAAD(new Buffer(test.aad, 'hex')); + encrypt.setAAD(Buffer.from(test.aad, 'hex')); var hex = encrypt.update(test.plain, 'ascii', 'hex'); hex += encrypt.final('hex'); var auth_tag = encrypt.getAuthTag(); @@ -77,10 +77,10 @@ for (var i in TEST_CASES) { (function() { var decrypt = crypto.createDecipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); - decrypt.setAuthTag(new Buffer(test.tag, 'hex')); + Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); + decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) - decrypt.setAAD(new Buffer(test.aad, 'hex')); + decrypt.setAAD(Buffer.from(test.aad, 'hex')); var msg = decrypt.update(test.ct, 'hex', 'ascii'); if (!test.tampered) { msg += decrypt.final('ascii'); @@ -100,7 +100,7 @@ for (var i in TEST_CASES) { } else { var encrypt = crypto.createCipher(test.algo, test.password); if (test.aad) - encrypt.setAAD(new Buffer(test.aad, 'hex')); + encrypt.setAAD(Buffer.from(test.aad, 'hex')); var hex = encrypt.update(test.plain, 'ascii', 'hex'); hex += encrypt.final('hex'); var auth_tag = encrypt.getAuthTag(); @@ -120,9 +120,9 @@ for (var i in TEST_CASES) { /not supported in FIPS mode/); } else { var decrypt = crypto.createDecipher(test.algo, test.password); - decrypt.setAuthTag(new Buffer(test.tag, 'hex')); + decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) - decrypt.setAAD(new Buffer(test.aad, 'hex')); + decrypt.setAAD(Buffer.from(test.aad, 'hex')); var msg = decrypt.update(test.ct, 'hex', 'ascii'); if (!test.tampered) { msg += decrypt.final('ascii'); @@ -149,13 +149,13 @@ for (var i in TEST_CASES) { encrypt.final(); assert.throws(function() { encrypt.getAuthTag(); }, / state/); assert.throws(function() { - encrypt.setAAD(new Buffer('123', 'ascii')); }, / state/); + encrypt.setAAD(Buffer.from('123', 'ascii')); }, / state/); })(); (function() { // trying to get tag before inputting all data: var encrypt = crypto.createCipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); encrypt.update('blah', 'ascii'); assert.throws(function() { encrypt.getAuthTag(); }, / state/); })(); @@ -163,15 +163,15 @@ for (var i in TEST_CASES) { (function() { // trying to set tag on encryption object: var encrypt = crypto.createCipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); assert.throws(function() { - encrypt.setAuthTag(new Buffer(test.tag, 'hex')); }, / state/); + encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, / state/); })(); (function() { // trying to read tag from decryption object: var decrypt = crypto.createDecipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); assert.throws(function() { decrypt.getAuthTag(); }, / state/); })(); } diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 3cb98db80aca55..6f235178b58829 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -55,8 +55,8 @@ assert.equal(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); // Test HMAC-SHA-* (rfc 4231 Test Cases) var rfc4231 = [ { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: new Buffer('4869205468657265', 'hex'), // 'Hi There' + key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: Buffer.from('4869205468657265', 'hex'), // 'Hi There' hmac: { sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', sha256: @@ -72,8 +72,8 @@ var rfc4231 = [ } }, { - key: new Buffer('4a656665', 'hex'), // 'Jefe' - data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + + key: Buffer.from('4a656665', 'hex'), // 'Jefe' + data: Buffer.from('7768617420646f2079612077616e7420666f72206e6f74686' + '96e673f', 'hex'), // 'what do ya want for nothing?' hmac: { sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', @@ -90,8 +90,8 @@ var rfc4231 = [ } }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: { @@ -109,9 +109,9 @@ var rfc4231 = [ } }, { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', 'hex'), hmac: { @@ -130,9 +130,9 @@ var rfc4231 = [ }, { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), // 'Test With Truncation' - data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), + data: Buffer.from('546573742057697468205472756e636174696f6e', 'hex'), hmac: { sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', sha256: 'a3b6167473100ee06e0c796c2955552b', @@ -142,14 +142,14 @@ var rfc4231 = [ truncate: true }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaa', 'hex'), // 'Test Using Larger Than Block-Size Key - Hash Key First' - data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + + data: Buffer.from('54657374205573696e67204c6172676572205468616e20426' + 'c6f636b2d53697a65204b6579202d2048617368204b657920' + '4669727374', 'hex'), hmac: { @@ -167,7 +167,7 @@ var rfc4231 = [ } }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + @@ -176,7 +176,7 @@ var rfc4231 = [ // 'This is a test using a larger than block-size key and a larger ' + // 'than block-size data. The key needs to be hashed before being ' + // 'used by the HMAC algorithm.' - data: new Buffer('5468697320697320612074657374207573696e672061206c6' + + data: Buffer.from('5468697320697320612074657374207573696e672061206c6' + '172676572207468616e20626c6f636b2d73697a65206b6579' + '20616e642061206c6172676572207468616e20626c6f636b2' + 'd73697a6520646174612e20546865206b6579206e65656473' + @@ -216,7 +216,7 @@ for (let i = 0, l = rfc4231.length; i < l; i++) { // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) var rfc2202_md5 = [ { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: '9294727a3638bb1c13f48ef8158bfc9d' }, @@ -226,28 +226,28 @@ var rfc2202_md5 = [ hmac: '750c783e6ab0b503eaa86e310a5db738' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: '56be34521d144c88dbb8c733f0e8b3f6' }, { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '697eaf0aca3a3aea3a75164746ffaa79' }, { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '56461ef2342edc00f9bab995690efd4c' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', @@ -256,7 +256,7 @@ var rfc2202_md5 = [ hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', @@ -269,7 +269,7 @@ var rfc2202_md5 = [ ]; var rfc2202_sha1 = [ { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' }, @@ -279,29 +279,29 @@ var rfc2202_sha1 = [ hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddd' + 'dddddddddd', 'hex'), hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' }, { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' }, { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', @@ -310,7 +310,7 @@ var rfc2202_sha1 = [ hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', @@ -364,7 +364,7 @@ assert.equal(a3, '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + 'Test SHA512 as assumed binary'); assert.deepEqual(a4, - new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), + Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), 'Test SHA1'); // Test multiple updates to same hash @@ -497,18 +497,18 @@ function testCipher4(key, iv) { if (!common.hasFipsCrypto) { testCipher1('MySecretKey123'); - testCipher1(new Buffer('MySecretKey123')); + testCipher1(Buffer.from('MySecretKey123')); testCipher2('0123456789abcdef'); - testCipher2(new Buffer('0123456789abcdef')); + testCipher2(Buffer.from('0123456789abcdef')); } testCipher3('0123456789abcd0123456789', '12345678'); -testCipher3('0123456789abcd0123456789', new Buffer('12345678')); -testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); -testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); +testCipher3('0123456789abcd0123456789', Buffer.from('12345678')); +testCipher3(Buffer.from('0123456789abcd0123456789'), '12345678'); +testCipher3(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678')); -testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); +testCipher4(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678')); // update() should only take buffers / strings diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index 5f867739abe7ed..aeebc1c4685925 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -67,10 +67,10 @@ function testCipher2(key) { } testCipher1('MySecretKey123'); -testCipher1(new Buffer('MySecretKey123')); +testCipher1(Buffer.from('MySecretKey123')); testCipher2('0123456789abcdef'); -testCipher2(new Buffer('0123456789abcdef')); +testCipher2(Buffer.from('0123456789abcdef')); // Base64 padding regression test, see #4837. (function() { diff --git a/test/parallel/test-crypto-cipheriv-decipheriv.js b/test/parallel/test-crypto-cipheriv-decipheriv.js index d325c0facf7e54..1d1aae091d17aa 100644 --- a/test/parallel/test-crypto-cipheriv-decipheriv.js +++ b/test/parallel/test-crypto-cipheriv-decipheriv.js @@ -58,8 +58,8 @@ function testCipher2(key, iv) { } testCipher1('0123456789abcd0123456789', '12345678'); -testCipher1('0123456789abcd0123456789', new Buffer('12345678')); -testCipher1(new Buffer('0123456789abcd0123456789'), '12345678'); -testCipher1(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); +testCipher1('0123456789abcd0123456789', Buffer.from('12345678')); +testCipher1(Buffer.from('0123456789abcd0123456789'), '12345678'); +testCipher1(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678')); -testCipher2(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); +testCipher2(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678')); diff --git a/test/parallel/test-crypto-dh-odd-key.js b/test/parallel/test-crypto-dh-odd-key.js index 503ba2fe089e3e..48d46f8237b2fd 100644 --- a/test/parallel/test-crypto-dh-odd-key.js +++ b/test/parallel/test-crypto-dh-odd-key.js @@ -9,8 +9,7 @@ if (!common.hasCrypto) { var crypto = require('crypto'); function test() { - var odd = new Buffer(39); - odd.fill('A'); + var odd = Buffer.alloc(39, 'A'); var c = crypto.createDiffieHellman(32); c.setPrivateKey(odd); diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 68394dd9bcaff9..1a96604ec1682f 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -86,7 +86,7 @@ assert.equal(bob.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); * The values below (modp2/modp2buf) are for a 1024 bits long prime from * RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */ var modp2 = crypto.createDiffieHellmanGroup('modp2'); -var modp2buf = new Buffer([ +var modp2buf = Buffer.from([ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, @@ -101,7 +101,7 @@ var modp2buf = new Buffer([ 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff ]); -var exmodp2 = crypto.createDiffieHellman(modp2buf, new Buffer([2])); +var exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2])); modp2.generateKeys(); exmodp2.generateKeys(); var modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex'); diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js index b2782e04f28ff0..11617be1cb2710 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -24,7 +24,7 @@ while (ucs2_control.length <= EXTERN_APEX) { // check resultant buffer and output string -var b = new Buffer(ucs2_control + ucs2_control, 'ucs2'); +var b = Buffer.from(ucs2_control + ucs2_control, 'ucs2'); // // Test updating from birant data diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index 3f8c902ab87bcf..fce11eca046786 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -47,7 +47,7 @@ assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', 'Test SHA256 as base64'); assert.deepEqual( a3, - new Buffer( + Buffer.from( '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + @@ -56,7 +56,7 @@ assert.deepEqual( 'binary'), 'Test SHA512 as assumed buffer'); assert.deepEqual(a4, - new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), + Buffer.from('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), 'Test SHA1'); // stream interface should produce the same result. diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index 600dd0dbb2c8bd..91ffc23e34bfa6 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -77,8 +77,8 @@ for (let i = 0, l = wikipedia.length; i < l; i++) { // Test HMAC-SHA-* (rfc 4231 Test Cases) var rfc4231 = [ { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: new Buffer('4869205468657265', 'hex'), // 'Hi There' + key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: Buffer.from('4869205468657265', 'hex'), // 'Hi There' hmac: { sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', sha256: @@ -94,8 +94,8 @@ var rfc4231 = [ } }, { - key: new Buffer('4a656665', 'hex'), // 'Jefe' - data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + + key: Buffer.from('4a656665', 'hex'), // 'Jefe' + data: Buffer.from('7768617420646f2079612077616e7420666f72206e6f74686' + '96e673f', 'hex'), // 'what do ya want for nothing?' hmac: { sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', @@ -112,8 +112,8 @@ var rfc4231 = [ } }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: { @@ -131,9 +131,9 @@ var rfc4231 = [ } }, { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', 'hex'), hmac: { @@ -152,9 +152,9 @@ var rfc4231 = [ }, { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), // 'Test With Truncation' - data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), + data: Buffer.from('546573742057697468205472756e636174696f6e', 'hex'), hmac: { sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', sha256: 'a3b6167473100ee06e0c796c2955552b', @@ -164,14 +164,14 @@ var rfc4231 = [ truncate: true }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaa', 'hex'), // 'Test Using Larger Than Block-Size Key - Hash Key First' - data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + + data: Buffer.from('54657374205573696e67204c6172676572205468616e20426' + 'c6f636b2d53697a65204b6579202d2048617368204b657920' + '4669727374', 'hex'), hmac: { @@ -189,7 +189,7 @@ var rfc4231 = [ } }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + @@ -198,7 +198,7 @@ var rfc4231 = [ // 'This is a test using a larger than block-size key and a larger ' + // 'than block-size data. The key needs to be hashed before being ' + // 'used by the HMAC algorithm.' - data: new Buffer('5468697320697320612074657374207573696e672061206c6' + + data: Buffer.from('5468697320697320612074657374207573696e672061206c6' + '172676572207468616e20626c6f636b2d73697a65206b6579' + '20616e642061206c6172676572207468616e20626c6f636b2' + 'd73697a6520646174612e20546865206b6579206e65656473' + @@ -243,7 +243,7 @@ for (let i = 0, l = rfc4231.length; i < l; i++) { // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) var rfc2202_md5 = [ { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: '9294727a3638bb1c13f48ef8158bfc9d' }, @@ -253,28 +253,28 @@ var rfc2202_md5 = [ hmac: '750c783e6ab0b503eaa86e310a5db738' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex'), hmac: '56be34521d144c88dbb8c733f0e8b3f6' }, { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '697eaf0aca3a3aea3a75164746ffaa79' }, { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '56461ef2342edc00f9bab995690efd4c' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', @@ -283,7 +283,7 @@ var rfc2202_md5 = [ hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', @@ -296,7 +296,7 @@ var rfc2202_md5 = [ ]; var rfc2202_sha1 = [ { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), data: 'Hi There', hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' }, @@ -306,29 +306,29 @@ var rfc2202_sha1 = [ hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: Buffer.from('ddddddddddddddddddddddddddddddddddddddddddddd' + 'ddddddddddddddddddddddddddddddddddddddddddddd' + 'dddddddddd', 'hex'), hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' }, { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + key: Buffer.from('0102030405060708090a0b0c0d0e0f10111213141516171819', 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + data: Buffer.from('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + 'cdcdcdcdcd', 'hex'), hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' }, { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + key: Buffer.from('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), data: 'Test With Truncation', hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', @@ -337,7 +337,7 @@ var rfc2202_sha1 = [ hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' }, { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + key: Buffer.from('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaa', diff --git a/test/parallel/test-crypto-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js index 550aa5c061f7ef..f5aa63474ed86e 100644 --- a/test/parallel/test-crypto-padding-aes256.js +++ b/test/parallel/test-crypto-padding-aes256.js @@ -11,8 +11,8 @@ var crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'buffer'; function aes256(decipherFinal) { - var iv = new Buffer('00000000000000000000000000000000', 'hex'); - var key = new Buffer('0123456789abcdef0123456789abcdef' + + var iv = Buffer.from('00000000000000000000000000000000', 'hex'); + var key = Buffer.from('0123456789abcdef0123456789abcdef' + '0123456789abcdef0123456789abcdef', 'hex'); function encrypt(val, pad) { diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index bd13ef0d912a61..e6f2fe6eb25131 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -29,7 +29,7 @@ var dsaKeyPemEncrypted = fs.readFileSync( // Test RSA encryption/decryption (function() { var input = 'I AM THE WALRUS'; - var bufferToEncrypt = new Buffer(input); + var bufferToEncrypt = Buffer.from(input); var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); @@ -55,12 +55,12 @@ var dsaKeyPemEncrypted = fs.readFileSync( encryptedBuffer = crypto.privateEncrypt({ key: rsaKeyPemEncrypted, - passphrase: new Buffer('password') + passphrase: Buffer.from('password') }, bufferToEncrypt); decryptedBufferWithPassword = crypto.publicDecrypt({ key: rsaKeyPemEncrypted, - passphrase: new Buffer('password') + passphrase: Buffer.from('password') }, encryptedBuffer); assert.equal(input, decryptedBufferWithPassword.toString()); @@ -95,22 +95,22 @@ var dsaKeyPemEncrypted = fs.readFileSync( encryptedBuffer = crypto.privateEncrypt({ key: rsaKeyPemEncrypted, - passphrase: new Buffer('password') + passphrase: Buffer.from('password') }, bufferToEncrypt); assert.throws(function() { crypto.publicDecrypt({ key: rsaKeyPemEncrypted, - passphrase: [].concat.apply([], new Buffer('password')) + passphrase: [].concat.apply([], Buffer.from('password')) }, encryptedBuffer); }); })(); function test_rsa(padding) { - var input = new Buffer(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); + var input = Buffer.allocUnsafe(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); for (var i = 0; i < input.length; i++) input[i] = (i * 7 + 11) & 0xff; - var bufferToEncrypt = new Buffer(input); + var bufferToEncrypt = Buffer.from(input); padding = constants[padding]; diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js index bf0fc2ca1d00df..60168069da1cb7 100644 --- a/test/parallel/test-crypto-stream.js +++ b/test/parallel/test-crypto-stream.js @@ -43,9 +43,9 @@ if (!common.hasFipsCrypto) { } // Decipher._flush() should emit an error event, not an exception. -const key = new Buffer('48fb56eb10ffeb13fc0ef551bbca3b1b', 'hex'); -const badkey = new Buffer('12341234123412341234123412341234', 'hex'); -const iv = new Buffer('6d358219d1f488f5f4eb12820a66d146', 'hex'); +const key = Buffer.from('48fb56eb10ffeb13fc0ef551bbca3b1b', 'hex'); +const badkey = Buffer.from('12341234123412341234123412341234', 'hex'); +const iv = Buffer.from('6d358219d1f488f5f4eb12820a66d146', 'hex'); const cipher = crypto.createCipheriv('aes-128-cbc', key, iv); const decipher = crypto.createDecipheriv('aes-128-cbc', badkey, iv); diff --git a/test/parallel/test-dgram-bytes-length.js b/test/parallel/test-dgram-bytes-length.js index 6527f628d01d2c..8e2233e9c4daad 100644 --- a/test/parallel/test-dgram-bytes-length.js +++ b/test/parallel/test-dgram-bytes-length.js @@ -3,7 +3,7 @@ require('../common'); var assert = require('assert'); var dgram = require('dgram'); -var message = new Buffer('Some bytes'); +var message = Buffer.from('Some bytes'); var client = dgram.createSocket('udp4'); client.send( message, diff --git a/test/parallel/test-dgram-close-is-not-callback.js b/test/parallel/test-dgram-close-is-not-callback.js index 6fc4901fa14404..29a364d8fab2ea 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -3,8 +3,7 @@ var assert = require('assert'); var common = require('../common'); var dgram = require('dgram'); -var buf = new Buffer(1024); -buf.fill(42); +var buf = Buffer.alloc(1024, 42); var socket = dgram.createSocket('udp4'); var closeEvents = 0; diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js index a84a3bc19e4bbc..7dbeee1efb9b61 100644 --- a/test/parallel/test-dgram-close.js +++ b/test/parallel/test-dgram-close.js @@ -6,8 +6,7 @@ const assert = require('assert'); const common = require('../common'); const dgram = require('dgram'); -var buf = new Buffer(1024); -buf.fill(42); +var buf = Buffer.alloc(1024, 42); var socket = dgram.createSocket('udp4'); var handle = socket._handle; diff --git a/test/parallel/test-dgram-empty-packet.js b/test/parallel/test-dgram-empty-packet.js index 66cdbb92ac8f1b..9a02799e2f35ca 100644 --- a/test/parallel/test-dgram-empty-packet.js +++ b/test/parallel/test-dgram-empty-packet.js @@ -29,9 +29,10 @@ client.on('message', function(buffer, bytes) { callback(); }); -client.send(new Buffer(1), 0, 0, common.PORT, '127.0.0.1', function(err, len) { - callback(); -}); +client.send( + Buffer.allocUnsafe(1), 0, 0, common.PORT, '127.0.0.1', (err, len) => { + callback(); + }); timer = setTimeout(function() { throw new Error('Timeout'); diff --git a/test/parallel/test-dgram-exclusive-implicit-bind.js b/test/parallel/test-dgram-exclusive-implicit-bind.js index cebb16204200f4..9a3cb91b3ac105 100644 --- a/test/parallel/test-dgram-exclusive-implicit-bind.js +++ b/test/parallel/test-dgram-exclusive-implicit-bind.js @@ -96,4 +96,4 @@ if (process.env.BOUND === 'y') { source.unref(); } -source.send(Buffer('abc'), 0, 3, common.PORT, '127.0.0.1'); +source.send(Buffer.from('abc'), 0, 3, common.PORT, '127.0.0.1'); diff --git a/test/parallel/test-dgram-implicit-bind.js b/test/parallel/test-dgram-implicit-bind.js index 8b78bd66c6f313..27cbdba398268e 100644 --- a/test/parallel/test-dgram-implicit-bind.js +++ b/test/parallel/test-dgram-implicit-bind.js @@ -22,8 +22,8 @@ target.on('message', function(buf) { target.on('listening', function() { // Second .send() call should not throw a bind error. - source.send(Buffer('abc'), 0, 3, common.PORT, '127.0.0.1'); - source.send(Buffer('def'), 0, 3, common.PORT, '127.0.0.1'); + source.send(Buffer.from('abc'), 0, 3, common.PORT, '127.0.0.1'); + source.send(Buffer.from('def'), 0, 3, common.PORT, '127.0.0.1'); }); target.bind(common.PORT); diff --git a/test/parallel/test-dgram-msgsize.js b/test/parallel/test-dgram-msgsize.js index 6330e2a82bdcc5..ec4021b99fd899 100644 --- a/test/parallel/test-dgram-msgsize.js +++ b/test/parallel/test-dgram-msgsize.js @@ -5,7 +5,7 @@ var dgram = require('dgram'); // Send a too big datagram. The destination doesn't matter because it's // not supposed to get sent out anyway. -var buf = Buffer(256 * 1024); +var buf = Buffer.allocUnsafe(256 * 1024); var sock = dgram.createSocket('udp4'); sock.send(buf, 0, buf.length, 12345, '127.0.0.1', common.mustCall(cb)); function cb(err) { diff --git a/test/parallel/test-dgram-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js index 88a28a757be2c0..e52bf7d69b3c6f 100644 --- a/test/parallel/test-dgram-oob-buffer.js +++ b/test/parallel/test-dgram-oob-buffer.js @@ -7,7 +7,7 @@ var common = require('../common'); var dgram = require('dgram'); var socket = dgram.createSocket('udp4'); -var buf = Buffer([1, 2, 3, 4]); +var buf = Buffer.from([1, 2, 3, 4]); function ok() {} socket.send(buf, 0, 0, common.PORT, '127.0.0.1', ok); // useful? no diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js index 080ac1d127061a..5d874855370ad9 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -3,7 +3,7 @@ require('../common'); var assert = require('assert'); var dgram = require('dgram'); -var buf = Buffer('test'); +var buf = Buffer.from('test'); var host = '127.0.0.1'; var sock = dgram.createSocket('udp4'); diff --git a/test/parallel/test-dgram-send-callback-buffer-length.js b/test/parallel/test-dgram-send-callback-buffer-length.js index 80c2d23e42ef55..f9883527b244c1 100644 --- a/test/parallel/test-dgram-send-callback-buffer-length.js +++ b/test/parallel/test-dgram-send-callback-buffer-length.js @@ -8,7 +8,7 @@ var client, timer, buf, len, offset; client = dgram.createSocket('udp4'); -buf = new Buffer(256); +buf = Buffer.allocUnsafe(256); offset = 20; len = buf.length - offset; diff --git a/test/parallel/test-dgram-send-callback-buffer.js b/test/parallel/test-dgram-send-callback-buffer.js index 1aea2f77ef806c..e877b8d73bdeb9 100644 --- a/test/parallel/test-dgram-send-callback-buffer.js +++ b/test/parallel/test-dgram-send-callback-buffer.js @@ -6,7 +6,7 @@ const dgram = require('dgram'); const client = dgram.createSocket('udp4'); -const buf = new Buffer(256); +const buf = Buffer.allocUnsafe(256); const onMessage = common.mustCall(function(err, bytes) { assert.equal(bytes, buf.length); diff --git a/test/parallel/test-dgram-send-callback-multi-buffer.js b/test/parallel/test-dgram-send-callback-multi-buffer.js index d3e276cfcd3618..c2a1a53e007ff5 100644 --- a/test/parallel/test-dgram-send-callback-multi-buffer.js +++ b/test/parallel/test-dgram-send-callback-multi-buffer.js @@ -16,12 +16,8 @@ const onMessage = common.mustCall(function(err, bytes) { client.close(); }); -const buf1 = new Buffer(256); - -const buf2 = new Buffer(256); - -buf1.fill('x'); -buf2.fill('y'); +const buf1 = Buffer.alloc(256, 'x'); +const buf2 = Buffer.alloc(256, 'y'); client.on('listening', function() { client.send([buf1, buf2], common.PORT, common.localhostIPv4, onMessage); diff --git a/test/parallel/test-dgram-send-default-host.js b/test/parallel/test-dgram-send-default-host.js index 0d493225132ca4..e6b6d7c9b45ab9 100644 --- a/test/parallel/test-dgram-send-default-host.js +++ b/test/parallel/test-dgram-send-default-host.js @@ -6,11 +6,10 @@ const dgram = require('dgram'); const client = dgram.createSocket('udp4'); -const toSend = [new Buffer(256), new Buffer(256), new Buffer(256), 'hello']; - -toSend[0].fill('x'); -toSend[1].fill('y'); -toSend[2].fill('z'); +const toSend = [Buffer.alloc(256, 'x'), + Buffer.alloc(256, 'y'), + Buffer.alloc(256, 'z'), + 'hello']; client.on('listening', function() { client.send(toSend[0], 0, toSend[0].length, common.PORT); diff --git a/test/parallel/test-dgram-send-empty-buffer.js b/test/parallel/test-dgram-send-empty-buffer.js index 6732bab159ee49..06b85ddb646030 100644 --- a/test/parallel/test-dgram-send-empty-buffer.js +++ b/test/parallel/test-dgram-send-empty-buffer.js @@ -16,7 +16,7 @@ client.on('message', function(buffer, bytes) { client.close(); }); -const buf = new Buffer(0); +const buf = Buffer.alloc(0); client.send(buf, 0, 0, common.PORT, '127.0.0.1', function(err, len) { }); const timer = setTimeout(function() { diff --git a/test/parallel/test-file-write-stream3.js b/test/parallel/test-file-write-stream3.js index f6b9de4ebe6209..2d65d3e2949dfe 100644 --- a/test/parallel/test-file-write-stream3.js +++ b/test/parallel/test-file-write-stream3.js @@ -72,7 +72,7 @@ function run_test_1() { throw err; }); - buffer = new Buffer(fileDataInitial); + buffer = Buffer.from(fileDataInitial); file.write(buffer); cb_occurred += 'write '; @@ -83,7 +83,7 @@ function run_test_1() { function run_test_2() { var file, buffer, options; - buffer = new Buffer('123456'); + buffer = Buffer.from('123456'); options = { start: 10, flags: 'r+' }; diff --git a/test/parallel/test-fs-append-file-sync.js b/test/parallel/test-fs-append-file-sync.js index 4c5ae870ecd5e2..576c406af26e96 100644 --- a/test/parallel/test-fs-append-file-sync.js +++ b/test/parallel/test-fs-append-file-sync.js @@ -41,7 +41,7 @@ assert.equal(Buffer.byteLength(data) + currentFileData.length, var filename3 = join(common.tmpDir, 'append-sync3.txt'); fs.writeFileSync(filename3, currentFileData); -var buf = new Buffer(data, 'utf8'); +var buf = Buffer.from(data, 'utf8'); fs.appendFileSync(filename3, buf); var fileData3 = fs.readFileSync(filename3); diff --git a/test/parallel/test-fs-append-file.js b/test/parallel/test-fs-append-file.js index 01742aa6f826c5..5970c8cec1515d 100644 --- a/test/parallel/test-fs-append-file.js +++ b/test/parallel/test-fs-append-file.js @@ -54,7 +54,7 @@ fs.appendFile(filename2, s, function(e) { var filename3 = join(common.tmpDir, 'append3.txt'); fs.writeFileSync(filename3, currentFileData); -var buf = new Buffer(s, 'utf8'); +var buf = Buffer.from(s, 'utf8'); fs.appendFile(filename3, buf, function(e) { if (e) throw e; diff --git a/test/parallel/test-fs-read-buffer-tostring-fail.js b/test/parallel/test-fs-read-buffer-tostring-fail.js index 1276390aefb6f9..3a3f77c05bb016 100644 --- a/test/parallel/test-fs-read-buffer-tostring-fail.js +++ b/test/parallel/test-fs-read-buffer-tostring-fail.js @@ -17,7 +17,7 @@ const stream = fs.createWriteStream(file, { }); const size = kStringMaxLength / 200; -const a = new Buffer(size).fill('a'); +const a = Buffer.alloc(size, 'a'); for (var i = 0; i < 201; i++) { stream.write(a); diff --git a/test/parallel/test-fs-read-buffer-zero-length.js b/test/parallel/test-fs-read-buffer-zero-length.js index 96586c25041c05..622aeb3a045a6a 100644 --- a/test/parallel/test-fs-read-buffer-zero-length.js +++ b/test/parallel/test-fs-read-buffer-zero-length.js @@ -6,14 +6,14 @@ const Buffer = require('buffer').Buffer; const fs = require('fs'); const filepath = path.join(common.fixturesDir, 'x.txt'); const fd = fs.openSync(filepath, 'r'); -const bufferAsync = new Buffer(0); -const bufferSync = new Buffer(0); +const bufferAsync = Buffer.alloc(0); +const bufferSync = Buffer.alloc(0); fs.read(fd, bufferAsync, 0, 0, 0, common.mustCall(function(err, bytesRead) { assert.equal(bytesRead, 0); - assert.deepEqual(bufferAsync, new Buffer(0)); + assert.deepEqual(bufferAsync, Buffer.alloc(0)); })); const r = fs.readSync(fd, bufferSync, 0, 0, 0); -assert.deepEqual(bufferSync, new Buffer(0)); +assert.deepEqual(bufferSync, Buffer.alloc(0)); assert.equal(r, 0); diff --git a/test/parallel/test-fs-read-buffer.js b/test/parallel/test-fs-read-buffer.js index 6b6f0572dacc8a..b9cc0752ec5ac3 100644 --- a/test/parallel/test-fs-read-buffer.js +++ b/test/parallel/test-fs-read-buffer.js @@ -7,19 +7,19 @@ const fs = require('fs'); const filepath = path.join(common.fixturesDir, 'x.txt'); const fd = fs.openSync(filepath, 'r'); const expected = 'xyz\n'; -const bufferAsync = new Buffer(expected.length); -const bufferSync = new Buffer(expected.length); +const bufferAsync = Buffer.allocUnsafe(expected.length); +const bufferSync = Buffer.allocUnsafe(expected.length); let readCalled = 0; fs.read(fd, bufferAsync, 0, expected.length, 0, function(err, bytesRead) { readCalled++; assert.equal(bytesRead, expected.length); - assert.deepEqual(bufferAsync, new Buffer(expected)); + assert.deepEqual(bufferAsync, Buffer.from(expected)); }); var r = fs.readSync(fd, bufferSync, 0, expected.length, 0); -assert.deepEqual(bufferSync, new Buffer(expected)); +assert.deepEqual(bufferSync, Buffer.from(expected)); assert.equal(r, expected.length); process.on('exit', function() { diff --git a/test/parallel/test-fs-read-stream-encoding.js b/test/parallel/test-fs-read-stream-encoding.js index 68699136ea6366..f8442ed548af5e 100644 --- a/test/parallel/test-fs-read-stream-encoding.js +++ b/test/parallel/test-fs-read-stream-encoding.js @@ -9,7 +9,7 @@ const encoding = 'base64'; const example = path.join(common.fixturesDir, 'x.txt'); const assertStream = new stream.Writable({ write: function(chunk, enc, next) { - const expected = new Buffer('xyz'); + const expected = Buffer.from('xyz'); assert(chunk.equals(expected)); } }); diff --git a/test/parallel/test-fs-readfile-tostring-fail.js b/test/parallel/test-fs-readfile-tostring-fail.js index 272aa865643e53..c61fa2c712714e 100644 --- a/test/parallel/test-fs-readfile-tostring-fail.js +++ b/test/parallel/test-fs-readfile-tostring-fail.js @@ -14,7 +14,7 @@ const stream = fs.createWriteStream(file, { }); const size = kStringMaxLength / 200; -const a = new Buffer(size).fill('a'); +const a = Buffer.alloc(size, 'a'); for (var i = 0; i < 201; i++) { stream.write(a); diff --git a/test/parallel/test-fs-readfile-unlink.js b/test/parallel/test-fs-readfile-unlink.js index dad993aa4ff2b2..50ad4172fc43dd 100644 --- a/test/parallel/test-fs-readfile-unlink.js +++ b/test/parallel/test-fs-readfile-unlink.js @@ -6,8 +6,7 @@ const path = require('path'); const dirName = path.resolve(common.fixturesDir, 'test-readfile-unlink'); const fileName = path.resolve(dirName, 'test.bin'); -var buf = new Buffer(512 * 1024); -buf.fill(42); +var buf = Buffer.alloc(512 * 1024, 42); try { fs.mkdirSync(dirName); diff --git a/test/parallel/test-fs-sir-writes-alot.js b/test/parallel/test-fs-sir-writes-alot.js index 1f949ed92a170f..8e1385ed4da2a0 100644 --- a/test/parallel/test-fs-sir-writes-alot.js +++ b/test/parallel/test-fs-sir-writes-alot.js @@ -16,7 +16,7 @@ var N = 10240, complete = 0; for (var i = 0; i < N; i++) { // Create a new buffer for each write. Before the write is actually // executed by the thread pool, the buffer will be collected. - var buffer = new Buffer(line); + var buffer = Buffer.from(line); fs.write(fd, buffer, 0, buffer.length, null, function(er, written) { complete++; if (complete === N) { @@ -44,4 +44,3 @@ process.on('exit', function() { // few... assert.ok(bytesChecked > 1000); }); - diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 54e16bd3875481..65d0c446f67d41 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -5,8 +5,7 @@ var path = require('path'); var fs = require('fs'); var tmp = common.tmpDir; var filename = path.resolve(tmp, 'truncate-file.txt'); -var data = new Buffer(1024 * 16); -data.fill('x'); +var data = Buffer.alloc(1024 * 16, 'x'); common.refreshTmpDir(); diff --git a/test/parallel/test-fs-write-buffer.js b/test/parallel/test-fs-write-buffer.js index 55ae8e287613a7..7dbe8ec3299c7b 100644 --- a/test/parallel/test-fs-write-buffer.js +++ b/test/parallel/test-fs-write-buffer.js @@ -5,7 +5,7 @@ const path = require('path'); const Buffer = require('buffer').Buffer; const fs = require('fs'); const filename = path.join(common.tmpDir, 'write.txt'); -const expected = new Buffer('hello'); +const expected = Buffer.from('hello'); let openCalled = 0; let writeCalled = 0; @@ -33,4 +33,3 @@ process.on('exit', function() { assert.equal(1, openCalled); assert.equal(1, writeCalled); }); - diff --git a/test/parallel/test-fs-write-file-buffer.js b/test/parallel/test-fs-write-file-buffer.js index 315ff87d782cd8..a23ccc21336976 100644 --- a/test/parallel/test-fs-write-file-buffer.js +++ b/test/parallel/test-fs-write-file-buffer.js @@ -27,7 +27,7 @@ data = data.join('\n'); common.refreshTmpDir(); -var buf = new Buffer(data, 'base64'); +var buf = Buffer.from(data, 'base64'); fs.writeFileSync(join(common.tmpDir, 'test.jpg'), buf); util.log('Done!'); diff --git a/test/parallel/test-fs-write-file.js b/test/parallel/test-fs-write-file.js index 14fb3e98acb626..eb4dd7db45575b 100644 --- a/test/parallel/test-fs-write-file.js +++ b/test/parallel/test-fs-write-file.js @@ -33,7 +33,7 @@ fs.writeFile(filename, s, function(e) { // test that writeFile accepts buffers var filename2 = join(common.tmpDir, 'test2.txt'); -var buf = new Buffer(s, 'utf8'); +var buf = Buffer.from(s, 'utf8'); fs.writeFile(filename2, buf, function(e) { if (e) throw e; diff --git a/test/parallel/test-fs-write-no-fd.js b/test/parallel/test-fs-write-no-fd.js index eb0ed5caeb6612..0aaec4b733356e 100644 --- a/test/parallel/test-fs-write-no-fd.js +++ b/test/parallel/test-fs-write-no-fd.js @@ -4,7 +4,7 @@ const fs = require('fs'); const assert = require('assert'); assert.throws(function() { - fs.write(null, new Buffer(1), 0, 1); + fs.write(null, Buffer.allocUnsafe(1), 0, 1); }, /TypeError/); assert.throws(function() { diff --git a/test/parallel/test-fs-write-stream-encoding.js b/test/parallel/test-fs-write-stream-encoding.js index 7dabebcd16b046..7bbffec1a5d3b7 100644 --- a/test/parallel/test-fs-write-stream-encoding.js +++ b/test/parallel/test-fs-write-stream-encoding.js @@ -23,7 +23,7 @@ const dummyWriteStream = fs.createWriteStream(dummyPath, { exampleReadStream.pipe(dummyWriteStream).on('finish', function() { const assertWriteStream = new stream.Writable({ write: function(chunk, enc, next) { - const expected = new Buffer('xyz\n'); + const expected = Buffer.from('xyz\n'); assert(chunk.equals(expected)); } }); diff --git a/test/parallel/test-fs-write-stream-err.js b/test/parallel/test-fs-write-stream-err.js index bc289d459677a3..c1151b12531f92 100644 --- a/test/parallel/test-fs-write-stream-err.js +++ b/test/parallel/test-fs-write-stream-err.js @@ -44,9 +44,9 @@ stream.on('error', common.mustCall(function(err_) { })); -stream.write(new Buffer(256), function() { +stream.write(Buffer.allocUnsafe(256), function() { console.error('first cb'); - stream.write(new Buffer(256), common.mustCall(function(err_) { + stream.write(Buffer.allocUnsafe(256), common.mustCall(function(err_) { console.error('second cb'); assert.equal(err_, err); })); diff --git a/test/parallel/test-fs-write-sync.js b/test/parallel/test-fs-write-sync.js index 83e60dd1cf915f..12f34f81d8e06b 100644 --- a/test/parallel/test-fs-write-sync.js +++ b/test/parallel/test-fs-write-sync.js @@ -16,7 +16,7 @@ assert.strictEqual(0, written); fs.writeSync(fd, foo); var bar = 'bár'; -written = fs.writeSync(fd, new Buffer(bar), 0, Buffer.byteLength(bar)); +written = fs.writeSync(fd, Buffer.from(bar), 0, Buffer.byteLength(bar)); assert.ok(written > 3); fs.closeSync(fd); diff --git a/test/parallel/test-http-buffer-sanity.js b/test/parallel/test-http-buffer-sanity.js index 98ce0f75b916a8..28f980a9d49db0 100644 --- a/test/parallel/test-http-buffer-sanity.js +++ b/test/parallel/test-http-buffer-sanity.js @@ -6,7 +6,7 @@ var http = require('http'); var bufferSize = 5 * 1024 * 1024; var measuredSize = 0; -var buffer = Buffer(bufferSize); +var buffer = Buffer.allocUnsafe(bufferSize); for (var i = 0; i < buffer.length; i++) { buffer[i] = i % 256; } diff --git a/test/parallel/test-http-byteswritten.js b/test/parallel/test-http-byteswritten.js index 41d8f4d40d1bf7..cd70bd9656f08d 100644 --- a/test/parallel/test-http-byteswritten.js +++ b/test/parallel/test-http-byteswritten.js @@ -24,7 +24,7 @@ var httpServer = http.createServer(function(req, res) { // Write 1.5mb to cause some requests to buffer // Also, mix up the encodings a bit. var chunk = new Array(1024 + 1).join('7'); - var bchunk = new Buffer(chunk); + var bchunk = Buffer.from(chunk); for (var i = 0; i < 1024; i++) { res.write(chunk); res.write(bchunk); @@ -39,4 +39,3 @@ var httpServer = http.createServer(function(req, res) { httpServer.listen(common.PORT, function() { http.get({ port: common.PORT }); }); - diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index 57d258671c298d..113ab750e20f14 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -41,7 +41,7 @@ server.on('listening', function() { }); }); - req.write(new Buffer(N)); + req.write(Buffer.allocUnsafe(N)); req.end(); }); diff --git a/test/parallel/test-http-outgoing-finish.js b/test/parallel/test-http-outgoing-finish.js index 2140759139c8ed..ec8c4c860788db 100644 --- a/test/parallel/test-http-outgoing-finish.js +++ b/test/parallel/test-http-outgoing-finish.js @@ -21,8 +21,7 @@ http.createServer(function(req, res) { }); }); -var buf = new Buffer(1024 * 16); -buf.fill('x'); +var buf = Buffer.alloc(1024 * 16, 'x'); function write(out) { var name = out.constructor.name; var finishEvent = false; diff --git a/test/parallel/test-http-parser-bad-ref.js b/test/parallel/test-http-parser-bad-ref.js index 545a9c1fef11c4..b7f132a3ea36fb 100644 --- a/test/parallel/test-http-parser-bad-ref.js +++ b/test/parallel/test-http-parser-bad-ref.js @@ -17,7 +17,7 @@ var headersComplete = 0; var messagesComplete = 0; function flushPool() { - new Buffer(Buffer.poolSize - 1); + Buffer.allocUnsafe(Buffer.poolSize - 1); gc(); } @@ -49,7 +49,7 @@ function demoBug(part1, part2) { // We use a function to eliminate references to the Buffer b // We want b to be GCed. The parser will hold a bad reference to it. (function() { - var b = Buffer(part1); + var b = Buffer.from(part1); flushPool(); console.log('parse the first part of the message'); @@ -59,7 +59,7 @@ function demoBug(part1, part2) { flushPool(); (function() { - var b = Buffer(part2); + var b = Buffer.from(part2); console.log('parse the second part of the message'); parser.execute(b, 0, b.length); diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index ca7afff3aac757..6c1466c4184a67 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -73,7 +73,7 @@ function expectBody(expected) { // Simple request test. // (function() { - var request = Buffer( + var request = Buffer.from( 'GET /hello HTTP/1.1' + CRLF + CRLF); @@ -111,7 +111,7 @@ function expectBody(expected) { // Simple response test. // (function() { - var request = Buffer( + var request = Buffer.from( 'HTTP/1.1 200 OK' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + @@ -144,7 +144,7 @@ function expectBody(expected) { // Response with no headers. // (function() { - var request = Buffer( + var request = Buffer.from( 'HTTP/1.0 200 Connection established' + CRLF + CRLF); @@ -169,7 +169,7 @@ function expectBody(expected) { // Trailing headers. // (function() { - var request = Buffer( + var request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + @@ -215,7 +215,7 @@ function expectBody(expected) { // Test header ordering. // (function() { - var request = Buffer( + var request = Buffer.from( 'GET / HTTP/1.0' + CRLF + 'X-Filler: 1337' + CRLF + 'X-Filler: 42' + CRLF + @@ -247,7 +247,7 @@ function expectBody(expected) { var lots_of_headers = 'X-Filler: 42' + CRLF; lots_of_headers = lots_of_headers.repeat(256); - var request = Buffer( + var request = Buffer.from( 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + lots_of_headers + CRLF); @@ -279,7 +279,7 @@ function expectBody(expected) { // Test request body // (function() { - var request = Buffer( + var request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: application/x-www-form-urlencoded' + CRLF + 'Content-Length: 15' + CRLF + @@ -311,7 +311,7 @@ function expectBody(expected) { // Test chunked request body // (function() { - var request = Buffer( + var request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -352,7 +352,7 @@ function expectBody(expected) { // Test chunked request body spread over multiple buffers (packets) // (function() { - var request = Buffer( + var request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -385,7 +385,7 @@ function expectBody(expected) { parser[kOnBody] = mustCall(onBody, body_parts.length); parser.execute(request, 0, request.length); - request = Buffer( + request = Buffer.from( '9' + CRLF + '123456789' + CRLF + 'C' + CRLF + @@ -402,7 +402,7 @@ function expectBody(expected) { // Stress test. // (function() { - var request = Buffer( + var request = Buffer.from( 'POST /helpme HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -462,7 +462,7 @@ function expectBody(expected) { // Byte by byte test. // (function() { - var request = Buffer( + var request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -515,7 +515,7 @@ function expectBody(expected) { // Test parser reinit sequence. // (function() { - var req1 = Buffer( + var req1 = Buffer.from( 'PUT /this HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -524,7 +524,7 @@ function expectBody(expected) { 'ping' + CRLF + '0' + CRLF); - var req2 = Buffer( + var req2 = Buffer.from( 'POST /that HTTP/1.0' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + @@ -568,7 +568,7 @@ function expectBody(expected) { // Test parser 'this' safety // https://github.com/joyent/node/issues/6690 assert.throws(function() { - var request = Buffer( + var request = Buffer.from( 'GET /hello HTTP/1.1' + CRLF + CRLF); diff --git a/test/parallel/test-http-pipeline-flood.js b/test/parallel/test-http-pipeline-flood.js index d291ccdb1776b5..47acb821068f01 100644 --- a/test/parallel/test-http-pipeline-flood.js +++ b/test/parallel/test-http-pipeline-flood.js @@ -26,7 +26,7 @@ switch (process.argv[2]) { function parent() { const http = require('http'); - const bigResponse = new Buffer(10240).fill('x'); + const bigResponse = Buffer.alloc(10240, 'x'); var requests = 0; var connections = 0; var backloggedReqs = 0; diff --git a/test/parallel/test-http-pipeline-regr-3332.js b/test/parallel/test-http-pipeline-regr-3332.js index 061e202d975f32..9247214ebf6285 100644 --- a/test/parallel/test-http-pipeline-regr-3332.js +++ b/test/parallel/test-http-pipeline-regr-3332.js @@ -4,8 +4,7 @@ const assert = require('assert'); const http = require('http'); const net = require('net'); -const big = new Buffer(16 * 1024); -big.fill('A'); +const big = Buffer.alloc(16 * 1024, 'A'); const COUNT = 1e4; diff --git a/test/parallel/test-http-pipeline-regr-3508.js b/test/parallel/test-http-pipeline-regr-3508.js index 74fe7586726cbd..b704293136b3d1 100644 --- a/test/parallel/test-http-pipeline-regr-3508.js +++ b/test/parallel/test-http-pipeline-regr-3508.js @@ -7,8 +7,7 @@ var once = false; var first = null; var second = null; -const chunk = new Buffer(1024); -chunk.fill('X'); +const chunk = Buffer.alloc(1024, 'X'); var size = 0; diff --git a/test/parallel/test-http-regr-gh-2821.js b/test/parallel/test-http-regr-gh-2821.js index 8725111324a869..7363f757f2b657 100644 --- a/test/parallel/test-http-regr-gh-2821.js +++ b/test/parallel/test-http-regr-gh-2821.js @@ -16,8 +16,7 @@ server.listen(common.PORT, function() { port: common.PORT }); - const payload = new Buffer(16390); - payload.fill('Й'); + const payload = Buffer.alloc(16390, 'Й'); req.write(payload); req.end(); }); diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js index 0befd951f0cf16..6aff0661dfc4cb 100644 --- a/test/parallel/test-http-res-write-end-dont-take-array.js +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -11,7 +11,7 @@ var server = http.createServer(function(req, res) { // write should accept string res.write('string'); // write should accept buffer - res.write(new Buffer('asdf')); + res.write(Buffer.from('asdf')); // write should not accept an Array assert.throws(function() { @@ -27,7 +27,7 @@ var server = http.createServer(function(req, res) { res.end('string'); } else if (test === 2) { // end should accept Buffer - res.end(new Buffer('asdf')); + res.end(Buffer.from('asdf')); } }); diff --git a/test/parallel/test-http-write-callbacks.js b/test/parallel/test-http-write-callbacks.js index 404396723e4416..6f36bcdd8f7dd4 100644 --- a/test/parallel/test-http-write-callbacks.js +++ b/test/parallel/test-http-write-callbacks.js @@ -36,7 +36,7 @@ server.on('checkContinue', function(req, res) { assert.ifError(er); res.write('foo', 'ascii', function(er) { assert.ifError(er); - res.end(new Buffer('bar'), 'buffer', function(er) { + res.end(Buffer.from('bar'), 'buffer', function(er) { serverEndCb = true; }); }); @@ -60,7 +60,7 @@ server.listen(common.PORT, function() { // ok, good to go. req.write('YmF6', 'base64', function(er) { assert.ifError(er); - req.write(new Buffer('quux'), function(er) { + req.write(Buffer.from('quux'), function(er) { assert.ifError(er); req.end('626c657267', 'hex', function(er) { assert.ifError(er); diff --git a/test/parallel/test-https-drain.js b/test/parallel/test-https-drain.js index 1ba5e2a4679f6d..562d4ce01b0d0e 100644 --- a/test/parallel/test-https-drain.js +++ b/test/parallel/test-https-drain.js @@ -37,7 +37,7 @@ server.listen(common.PORT, function() { console.error('paused'); send(); function send() { - if (req.write(new Buffer(bufSize))) { + if (req.write(Buffer.allocUnsafe(bufSize))) { sent += bufSize; assert.ok(sent < 100 * 1024 * 1024); // max 100MB return process.nextTick(send); diff --git a/test/parallel/test-https-resume-after-renew.js b/test/parallel/test-https-resume-after-renew.js index 23626ccb40cb51..6a1238f6e8a7be 100644 --- a/test/parallel/test-https-resume-after-renew.js +++ b/test/parallel/test-https-resume-after-renew.js @@ -14,17 +14,14 @@ var server = https.createServer(options, function(req, res) { res.end('hello'); }); -var aes = new Buffer(16); -aes.fill('S'); -var hmac = new Buffer(16); -hmac.fill('H'); +var aes = Buffer.alloc(16, 'S'); +var hmac = Buffer.alloc(16, 'H'); server._sharedCreds.context.enableTicketKeyCallback(); server._sharedCreds.context.onticketkeycallback = function(name, iv, enc) { if (enc) { - var newName = new Buffer(16); + var newName = Buffer.alloc(16, 'A'); var newIV = crypto.randomBytes(16); - newName.fill('A'); } else { // Renew return [ 2, hmac, aes ]; diff --git a/test/parallel/test-https-truncate.js b/test/parallel/test-https-truncate.js index 83506c65d6f3cc..58fcf010f6ea5b 100644 --- a/test/parallel/test-https-truncate.js +++ b/test/parallel/test-https-truncate.js @@ -16,7 +16,7 @@ var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); var PORT = common.PORT; // number of bytes discovered empirically to trigger the bug -var data = new Buffer(1024 * 32 + 1); +var data = Buffer.allocUnsafe(1024 * 32 + 1); httpsTest(); diff --git a/test/parallel/test-net-connect-buffer.js b/test/parallel/test-net-connect-buffer.js index 304401f56ef50d..bd8efe1643441f 100644 --- a/test/parallel/test-net-connect-buffer.js +++ b/test/parallel/test-net-connect-buffer.js @@ -77,13 +77,13 @@ tcp.listen(common.PORT, function() { dataWritten = true; assert.ok(connectHappened); console.error('socket.bytesWritten', socket.bytesWritten); - //assert.equal(socket.bytesWritten, Buffer(a + b).length); + //assert.equal(socket.bytesWritten, Buffer.from(a + b).length); console.error('data written'); }); console.error('socket.bytesWritten', socket.bytesWritten); console.error('write returned', r); - assert.equal(socket.bytesWritten, Buffer(a).length); + assert.equal(socket.bytesWritten, Buffer.from(a).length); assert.equal(false, r); socket.end(b); diff --git a/test/parallel/test-net-error-twice.js b/test/parallel/test-net-error-twice.js index 28e90ddd611ba9..54c100d7b10b89 100644 --- a/test/parallel/test-net-error-twice.js +++ b/test/parallel/test-net-error-twice.js @@ -3,9 +3,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -const buf = new Buffer(10 * 1024 * 1024); - -buf.fill(0x62); +const buf = Buffer.alloc(10 * 1024 * 1024, 0x62); const errs = []; var clientSocket; diff --git a/test/parallel/test-net-stream.js b/test/parallel/test-net-stream.js index 9075d99471540a..c4d29b90778ab6 100644 --- a/test/parallel/test-net-stream.js +++ b/test/parallel/test-net-stream.js @@ -21,8 +21,7 @@ assert.equal(9, s.server.connections); var SIZE = 2E6; var N = 10; -var buf = new Buffer(SIZE); -buf.fill(0x61); // 'a' +var buf = Buffer.alloc(SIZE, 'a'); var server = net.createServer(function(socket) { socket.setNoDelay(); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 8ded93ee71a8d3..f7bb25c7a75b9c 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -7,8 +7,7 @@ var SIZE = 2E5; var N = 10; var flushed = 0; var received = 0; -var buf = new Buffer(SIZE); -buf.fill(0x61); // 'a' +var buf = Buffer.alloc(SIZE, 'a'); var server = net.createServer(function(socket) { socket.setNoDelay(); diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 0bdcfe1bc4700f..1b0a46eaa2b262 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -230,7 +230,7 @@ function isWarned(emitter) { }); // sending a multi-byte utf8 char over multiple writes - var buf = Buffer('☮', 'utf8'); + var buf = Buffer.from('☮', 'utf8'); fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); callCount = 0; @@ -239,7 +239,7 @@ function isWarned(emitter) { assert.equal(line, buf.toString('utf8')); }); [].forEach.call(buf, function(i) { - fi.emit('data', Buffer([i])); + fi.emit('data', Buffer.from([i])); }); assert.equal(callCount, 0); fi.emit('data', '\n'); diff --git a/test/parallel/test-regress-GH-io-1811.js b/test/parallel/test-regress-GH-io-1811.js index bfbf99243320d4..a8966da10ba1f7 100644 --- a/test/parallel/test-regress-GH-io-1811.js +++ b/test/parallel/test-regress-GH-io-1811.js @@ -11,7 +11,7 @@ buffer.kMaxLength = 128; const zlib = require('zlib'); buffer.kMaxLength = oldkMaxLength; -const encoded = new Buffer('H4sIAAAAAAAAA0tMHFgAAIw2K/GAAAAA', 'base64'); +const encoded = Buffer.from('H4sIAAAAAAAAA0tMHFgAAIw2K/GAAAAA', 'base64'); // Async zlib.gunzip(encoded, function(err) { diff --git a/test/parallel/test-stream-big-packet.js b/test/parallel/test-stream-big-packet.js index e64f4aa34fd481..8dc910022d2821 100644 --- a/test/parallel/test-stream-big-packet.js +++ b/test/parallel/test-stream-big-packet.js @@ -35,8 +35,7 @@ s1.pipe(s3); s2.pipe(s3, {end: false}); // We must write a buffer larger than highWaterMark -var big = new Buffer(s1._writableState.highWaterMark + 1); -big.fill('x'); +var big = Buffer.alloc(s1._writableState.highWaterMark + 1, 'x'); // Since big is larger than highWaterMark, it will be buffered internally. assert(!s1.write(big)); diff --git a/test/parallel/test-stream-pipe-cleanup-pause.js b/test/parallel/test-stream-pipe-cleanup-pause.js index 332930c813a3dd..3085ed5f9a9c39 100644 --- a/test/parallel/test-stream-pipe-cleanup-pause.js +++ b/test/parallel/test-stream-pipe-cleanup-pause.js @@ -9,7 +9,7 @@ const writer2 = new stream.Writable(); // 560000 is chosen here because it is larger than the (default) highWaterMark // and will cause `.write()` to return false // See: https://github.com/nodejs/node/issues/2323 -const buffer = new Buffer(560000); +const buffer = Buffer.allocUnsafe(560000); reader._read = function(n) {}; diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index 10d314f4eec254..957f4097818bfc 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -17,7 +17,7 @@ var Readable = require('stream').Readable; }; // This triggers a 'readable' event, which is lost. - r.push(new Buffer('blerg')); + r.push(Buffer.from('blerg')); var caughtReadable = false; setTimeout(function() { @@ -51,7 +51,7 @@ var Readable = require('stream').Readable; }; // This triggers a 'readable' event, which is lost. - r.push(new Buffer('bl')); + r.push(Buffer.from('bl')); var caughtReadable = false; setTimeout(function() { @@ -84,7 +84,7 @@ var Readable = require('stream').Readable; }; // This triggers a 'readable' event, which is lost. - r.push(new Buffer('blerg')); + r.push(Buffer.from('blerg')); r.push(null); var caughtReadable = false; diff --git a/test/parallel/test-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js index 57e295e5383550..0c0b16e8f5ca7e 100644 --- a/test/parallel/test-stream-readable-flow-recursion.js +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -22,7 +22,7 @@ stream._read = function(size) { if (size === 0) stream.push(null); else - stream.push(new Buffer(size)); + stream.push(Buffer.allocUnsafe(size)); }; var depth = 0; diff --git a/test/parallel/test-stream-transform-constructor-set-methods.js b/test/parallel/test-stream-transform-constructor-set-methods.js index bf76b93690c840..720357a01b9839 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -21,7 +21,7 @@ var t = new Transform({ flush: _flush }); -t.end(new Buffer('blerg')); +t.end(Buffer.from('blerg')); t.resume(); process.on('exit', function() { diff --git a/test/parallel/test-stream-transform-split-objectmode.js b/test/parallel/test-stream-transform-split-objectmode.js index 4e33028da2f7de..96362302241869 100644 --- a/test/parallel/test-stream-transform-split-objectmode.js +++ b/test/parallel/test-stream-transform-split-objectmode.js @@ -21,7 +21,7 @@ parser.on('data', function(obj) { parsed = obj; }); -parser.end(new Buffer([42])); +parser.end(Buffer.from([42])); process.on('exit', function() { assert(parsed.val === 42); @@ -36,7 +36,7 @@ assert(serializer._readableState.highWaterMark === (16 * 1024)); assert(serializer._writableState.highWaterMark === 16); serializer._transform = function(obj, _, callback) { - callback(null, new Buffer([obj.val])); + callback(null, Buffer.from([obj.val])); }; var serialized; diff --git a/test/parallel/test-stream-unshift-empty-chunk.js b/test/parallel/test-stream-unshift-empty-chunk.js index 0da979e337486e..692b1aa57fac33 100644 --- a/test/parallel/test-stream-unshift-empty-chunk.js +++ b/test/parallel/test-stream-unshift-empty-chunk.js @@ -2,14 +2,13 @@ require('../common'); var assert = require('assert'); -// This test verifies that stream.unshift(Buffer(0)) or +// This test verifies that stream.unshift(Buffer.alloc(0)) or // stream.unshift('') does not set state.reading=false. var Readable = require('stream').Readable; var r = new Readable(); var nChunks = 10; -var chunk = new Buffer(10); -chunk.fill('x'); +var chunk = Buffer.alloc(10, 'x'); r._read = function(n) { setTimeout(function() { @@ -28,8 +27,7 @@ r.on('readable', function() { // stream, like a parser might do. We just fill it with // 'y' so that it's easy to see which bits were touched, // and which were not. - var putBack = new Buffer(readAll ? 0 : 5); - putBack.fill('y'); + var putBack = Buffer.alloc(readAll ? 0 : 5, 'y'); readAll = !readAll; r.unshift(putBack); } diff --git a/test/parallel/test-stream-unshift-read-race.js b/test/parallel/test-stream-unshift-read-race.js index 8239a380def66c..c21bb60cc61f45 100644 --- a/test/parallel/test-stream-unshift-read-race.js +++ b/test/parallel/test-stream-unshift-read-race.js @@ -14,7 +14,7 @@ var hwm = 10; var r = stream.Readable({ highWaterMark: hwm }); var chunks = 10; -var data = new Buffer(chunks * hwm + Math.ceil(hwm / 2)); +var data = Buffer.allocUnsafe(chunks * hwm + Math.ceil(hwm / 2)); for (var i = 0; i < data.length; i++) { var c = 'asdf'.charCodeAt(i % 4); data[i] = c; @@ -48,7 +48,7 @@ r._read = function(n) { function pushError() { assert.throws(function() { - r.push(new Buffer(1)); + r.push(Buffer.allocUnsafe(1)); }); } @@ -64,7 +64,7 @@ var ended = false; r.on('end', function() { assert(!ended, 'end emitted more than once'); assert.throws(function() { - r.unshift(new Buffer(1)); + r.unshift(Buffer.allocUnsafe(1)); }); ended = true; w.end(); @@ -75,7 +75,7 @@ r.on('readable', function() { while (null !== (chunk = r.read(10))) { w.write(chunk); if (chunk.length > 4) - r.unshift(new Buffer('1234')); + r.unshift(Buffer.from('1234')); } }); diff --git a/test/parallel/test-stream-writable-constructor-set-methods.js b/test/parallel/test-stream-writable-constructor-set-methods.js index 4a5f90216070c5..7d7dfb5f1ccfa0 100644 --- a/test/parallel/test-stream-writable-constructor-set-methods.js +++ b/test/parallel/test-stream-writable-constructor-set-methods.js @@ -10,7 +10,7 @@ function _write(d, e, n) { } var w = new Writable({ write: _write }); -w.end(new Buffer('blerg')); +w.end(Buffer.from('blerg')); var _writevCalled = false; var dLength = 0; @@ -22,8 +22,8 @@ function _writev(d, n) { var w2 = new Writable({ writev: _writev }); w2.cork(); -w2.write(new Buffer('blerg')); -w2.write(new Buffer('blerg')); +w2.write(Buffer.from('blerg')); +w2.write(Buffer.from('blerg')); w2.end(); process.on('exit', function() { diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 2aa992b4a9a785..0a51478b7ea456 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -82,7 +82,7 @@ function test(decode, uncork, multi, next) { if (multi) w.cork(); - w.write(new Buffer('!'), 'buffer', cnt('!')); + w.write(Buffer.from('!'), 'buffer', cnt('!')); w.write('\nand then...', 'binary', cnt('and then')); if (multi) diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 0f9f56b3e70730..07244dc0fbbf78 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -14,7 +14,7 @@ src._read = function(n) { if (!hasRead) { hasRead = true; process.nextTick(function() { - src.push(new Buffer('1')); + src.push(Buffer.from('1')); src.push(null); }); } diff --git a/test/parallel/test-stream2-compatibility.js b/test/parallel/test-stream2-compatibility.js index 2d62d639077634..77312456590b25 100644 --- a/test/parallel/test-stream2-compatibility.js +++ b/test/parallel/test-stream2-compatibility.js @@ -10,8 +10,7 @@ var ondataCalled = 0; function TestReader() { R.apply(this); - this._buffer = new Buffer(100); - this._buffer.fill('x'); + this._buffer = Buffer.alloc(100, 'x'); this.on('data', function() { ondataCalled++; @@ -22,7 +21,7 @@ util.inherits(TestReader, R); TestReader.prototype._read = function(n) { this.push(this._buffer); - this._buffer = new Buffer(0); + this._buffer = Buffer.alloc(0); }; var reader = new TestReader(); diff --git a/test/parallel/test-stream2-finish-pipe.js b/test/parallel/test-stream2-finish-pipe.js index 63c78759cab60d..fb489978f498ad 100644 --- a/test/parallel/test-stream2-finish-pipe.js +++ b/test/parallel/test-stream2-finish-pipe.js @@ -5,7 +5,7 @@ var Buffer = require('buffer').Buffer; var r = new stream.Readable(); r._read = function(size) { - r.push(new Buffer(size)); + r.push(Buffer.allocUnsafe(size)); }; var w = new stream.Writable(); diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 6a38baac5dacbc..0f28db508a4cde 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -49,7 +49,7 @@ function push() { } console.error(' push #%d', pushes); - if (r.push(new Buffer(PUSHSIZE))) + if (r.push(Buffer.allocUnsafe(PUSHSIZE))) setTimeout(push); } diff --git a/test/parallel/test-stream2-pipe-error-handling.js b/test/parallel/test-stream2-pipe-error-handling.js index 7d7cfb6b2b3307..65397566c23ca2 100644 --- a/test/parallel/test-stream2-pipe-error-handling.js +++ b/test/parallel/test-stream2-pipe-error-handling.js @@ -10,7 +10,7 @@ var stream = require('stream'); source._read = function(n) { n = Math.min(count, n); count -= n; - source.push(new Buffer(n)); + source.push(Buffer.allocUnsafe(n)); }; var unpipedDest; @@ -50,7 +50,7 @@ var stream = require('stream'); source._read = function(n) { n = Math.min(count, n); count -= n; - source.push(new Buffer(n)); + source.push(Buffer.allocUnsafe(n)); }; var unpipedDest; diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js index 4bce87ffb9dffd..6ed645948c2814 100644 --- a/test/parallel/test-stream2-read-sync-stack.js +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -11,7 +11,7 @@ process.maxTickDepth = N + 2; var reads = 0; r._read = function(n) { - var chunk = reads++ === N ? null : new Buffer(1); + var chunk = reads++ === N ? null : Buffer.allocUnsafe(1); r.push(chunk); }; diff --git a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js index 18012df3a41d89..7c892857860df1 100644 --- a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js +++ b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js @@ -10,9 +10,9 @@ test2(); function test1() { const r = new Readable(); - // should not end when we get a Buffer(0) or '' as the _read result - // that just means that there is *temporarily* no data, but to go - // ahead and try again later. + // should not end when we get a Buffer.alloc(0) or '' as the _read + // result that just means that there is *temporarily* no data, but to + // go ahead and try again later. // // note that this is very unusual. it only works for crypto streams // because the other side of the stream will call read(0) to cycle @@ -20,7 +20,7 @@ function test1() { // r.read(0) again later, otherwise there is no more work being done // and the process just exits. - const buf = Buffer(5).fill('x'); + const buf = Buffer.alloc(5, 'x'); let reads = 5; const timeout = common.platformTimeout(50); r._read = function(n) { @@ -31,16 +31,16 @@ function test1() { return r.push(buf); case 2: setTimeout(r.read.bind(r, 0), timeout); - return r.push(new Buffer(0)); // Not-EOF! + return r.push(Buffer.alloc(0)); // Not-EOF! case 3: setTimeout(r.read.bind(r, 0), timeout); return process.nextTick(function() { - return r.push(new Buffer(0)); + return r.push(Buffer.alloc(0)); }); case 4: setTimeout(r.read.bind(r, 0), timeout); return setTimeout(function() { - return r.push(new Buffer(0)); + return r.push(Buffer.alloc(0)); }); case 5: return setTimeout(function() { @@ -76,7 +76,7 @@ function test2() { if (!reads--) return r.push(null); // EOF else - return r.push(new Buffer('x')); + return r.push(Buffer.from('x')); }; var results = []; diff --git a/test/parallel/test-stream2-readable-from-list.js b/test/parallel/test-stream2-readable-from-list.js index ab9d9c5d72cae1..e22c7a51940966 100644 --- a/test/parallel/test-stream2-readable-from-list.js +++ b/test/parallel/test-stream2-readable-from-list.js @@ -39,10 +39,10 @@ process.nextTick(run); test('buffers', function(t) { - var list = [ new Buffer('foog'), - new Buffer('bark'), - new Buffer('bazy'), - new Buffer('kuel') ]; + var list = [ Buffer.from('foog'), + Buffer.from('bark'), + Buffer.from('bazy'), + Buffer.from('kuel') ]; // read more than the first element. var ret = fromList(6, { buffer: list, length: 16 }); diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js index 399771e46a11ed..03c57cbfbf7930 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -9,7 +9,7 @@ var r = new Readable(); var N = 256; var reads = 0; r._read = function(n) { - return r.push(++reads === N ? null : new Buffer(1)); + return r.push(++reads === N ? null : Buffer.allocUnsafe(1)); }; var rended = false; diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index 1953503ef9be2e..e337485b63f21e 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -6,7 +6,7 @@ var Readable = require('_stream_readable'); var len = 0; var chunks = new Array(10); for (var i = 1; i <= 10; i++) { - chunks[i - 1] = new Buffer(i); + chunks[i - 1] = Buffer.allocUnsafe(i); len += i; } diff --git a/test/parallel/test-stream2-readable-wrap.js b/test/parallel/test-stream2-readable-wrap.js index acf1cfdb030439..60f994f5ab0ae7 100644 --- a/test/parallel/test-stream2-readable-wrap.js +++ b/test/parallel/test-stream2-readable-wrap.js @@ -77,8 +77,8 @@ function runTest(highWaterMark, objectMode, produce) { } } -runTest(100, false, function() { return new Buffer(100); }); -runTest(10, false, function() { return new Buffer('xxxxxxxxxx'); }); +runTest(100, false, function() { return Buffer.allocUnsafe(100); }); +runTest(10, false, function() { return Buffer.from('xxxxxxxxxx'); }); runTest(1, true, function() { return { foo: 'bar' }; }); var objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js index 40e09035a98e90..dd27c1bb297801 100644 --- a/test/parallel/test-stream2-set-encoding.js +++ b/test/parallel/test-stream2-set-encoding.js @@ -66,8 +66,7 @@ TestReader.prototype._read = function(n) { } this.pos += n; - var ret = new Buffer(n); - ret.fill('a'); + var ret = Buffer.alloc(n, 'a'); console.log('this.push(ret)', ret); diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 11ee45915c8395..c52d09e9f68370 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -54,7 +54,7 @@ test('writable side consumption', function(t) { }; for (var i = 1; i <= 10; i++) { - tx.write(new Buffer(i)); + tx.write(Buffer.allocUnsafe(i)); } tx.end(); @@ -71,10 +71,10 @@ test('writable side consumption', function(t) { test('passthrough', function(t) { var pt = new PassThrough(); - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); + pt.write(Buffer.from('foog')); + pt.write(Buffer.from('bark')); + pt.write(Buffer.from('bazy')); + pt.write(Buffer.from('kuel')); pt.end(); t.equal(pt.read(5).toString(), 'foogb'); @@ -109,16 +109,15 @@ test('object passthrough', function(t) { test('simple transform', function(t) { var pt = new Transform(); pt._transform = function(c, e, cb) { - var ret = new Buffer(c.length); - ret.fill('x'); + var ret = Buffer.alloc(c.length, 'x'); pt.push(ret); cb(); }; - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); + pt.write(Buffer.from('foog')); + pt.write(Buffer.from('bark')); + pt.write(Buffer.from('bazy')); + pt.write(Buffer.from('kuel')); pt.end(); t.equal(pt.read(5).toString(), 'xxxxx'); @@ -163,10 +162,10 @@ test('async passthrough', function(t) { }, 10); }; - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); + pt.write(Buffer.from('foog')); + pt.write(Buffer.from('bark')); + pt.write(Buffer.from('bazy')); + pt.write(Buffer.from('kuel')); pt.end(); pt.on('finish', function() { @@ -192,10 +191,10 @@ test('assymetric transform (expand)', function(t) { }, 10); }; - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); + pt.write(Buffer.from('foog')); + pt.write(Buffer.from('bark')); + pt.write(Buffer.from('bazy')); + pt.write(Buffer.from('kuel')); pt.end(); pt.on('finish', function() { @@ -224,7 +223,7 @@ test('assymetric transform (compress)', function(t) { setTimeout(function() { this.state += s.charAt(0); if (this.state.length === 3) { - pt.push(new Buffer(this.state)); + pt.push(Buffer.from(this.state)); this.state = ''; } cb(); @@ -233,25 +232,25 @@ test('assymetric transform (compress)', function(t) { pt._flush = function(cb) { // just output whatever we have. - pt.push(new Buffer(this.state)); + pt.push(Buffer.from(this.state)); this.state = ''; cb(); }; - pt.write(new Buffer('aaaa')); - pt.write(new Buffer('bbbb')); - pt.write(new Buffer('cccc')); - pt.write(new Buffer('dddd')); - pt.write(new Buffer('eeee')); - pt.write(new Buffer('aaaa')); - pt.write(new Buffer('bbbb')); - pt.write(new Buffer('cccc')); - pt.write(new Buffer('dddd')); - pt.write(new Buffer('eeee')); - pt.write(new Buffer('aaaa')); - pt.write(new Buffer('bbbb')); - pt.write(new Buffer('cccc')); - pt.write(new Buffer('dddd')); + pt.write(Buffer.from('aaaa')); + pt.write(Buffer.from('bbbb')); + pt.write(Buffer.from('cccc')); + pt.write(Buffer.from('dddd')); + pt.write(Buffer.from('eeee')); + pt.write(Buffer.from('aaaa')); + pt.write(Buffer.from('bbbb')); + pt.write(Buffer.from('cccc')); + pt.write(Buffer.from('dddd')); + pt.write(Buffer.from('eeee')); + pt.write(Buffer.from('aaaa')); + pt.write(Buffer.from('bbbb')); + pt.write(Buffer.from('cccc')); + pt.write(Buffer.from('dddd')); pt.end(); // 'abcdeabcdeabcd' @@ -285,8 +284,8 @@ test('complex transform', function(t) { pt.once('readable', function() { process.nextTick(function() { - pt.write(new Buffer('d')); - pt.write(new Buffer('ef'), function() { + pt.write(Buffer.from('d')); + pt.write(Buffer.from('ef'), function() { pt.end(); t.end(); }); @@ -295,7 +294,7 @@ test('complex transform', function(t) { }); }); - pt.write(new Buffer('abc')); + pt.write(Buffer.from('abc')); }); @@ -307,10 +306,10 @@ test('passthrough event emission', function(t) { emits++; }); - pt.write(new Buffer('foog')); + pt.write(Buffer.from('foog')); console.error('need emit 0'); - pt.write(new Buffer('bark')); + pt.write(Buffer.from('bark')); console.error('should have emitted readable now 1 === %d', emits); t.equal(emits, 1); @@ -320,9 +319,9 @@ test('passthrough event emission', function(t) { console.error('need emit 1'); - pt.write(new Buffer('bazy')); + pt.write(Buffer.from('bazy')); console.error('should have emitted, but not again'); - pt.write(new Buffer('kuel')); + pt.write(Buffer.from('kuel')); console.error('should have emitted readable now 2 === %d', emits); t.equal(emits, 2); @@ -353,9 +352,9 @@ test('passthrough event emission reordered', function(t) { emits++; }); - pt.write(new Buffer('foog')); + pt.write(Buffer.from('foog')); console.error('need emit 0'); - pt.write(new Buffer('bark')); + pt.write(Buffer.from('bark')); console.error('should have emitted readable now 1 === %d', emits); t.equal(emits, 1); @@ -380,10 +379,10 @@ test('passthrough event emission reordered', function(t) { }); pt.end(); }); - pt.write(new Buffer('kuel')); + pt.write(Buffer.from('kuel')); }); - pt.write(new Buffer('bazy')); + pt.write(Buffer.from('bazy')); }); test('passthrough facaded', function(t) { @@ -399,13 +398,13 @@ test('passthrough facaded', function(t) { t.end(); }); - pt.write(new Buffer('foog')); + pt.write(Buffer.from('foog')); setTimeout(function() { - pt.write(new Buffer('bark')); + pt.write(Buffer.from('bark')); setTimeout(function() { - pt.write(new Buffer('bazy')); + pt.write(Buffer.from('bazy')); setTimeout(function() { - pt.write(new Buffer('kuel')); + pt.write(Buffer.from('kuel')); setTimeout(function() { pt.end(); }, 10); diff --git a/test/parallel/test-stream2-unpipe-leak.js b/test/parallel/test-stream2-unpipe-leak.js index 3b529bac1f2e9c..d94e39f7667df4 100644 --- a/test/parallel/test-stream2-unpipe-leak.js +++ b/test/parallel/test-stream2-unpipe-leak.js @@ -3,7 +3,7 @@ require('../common'); var assert = require('assert'); var stream = require('stream'); -var chunk = new Buffer('hallo'); +var chunk = Buffer.from('hallo'); var util = require('util'); diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js index 81e57d06eb3bec..062e69f78c84fa 100644 --- a/test/parallel/test-stream2-writable.js +++ b/test/parallel/test-stream2-writable.js @@ -154,7 +154,7 @@ test('write bufferize', function(t) { chunks.forEach(function(chunk, i) { var enc = encodings[ i % encodings.length ]; - chunk = new Buffer(chunk); + chunk = Buffer.from(chunk); tw.write(chunk.toString(enc), enc); }); t.end(); @@ -168,7 +168,7 @@ test('write no bufferize', function(t) { tw._write = function(chunk, encoding, cb) { assert(typeof chunk === 'string'); - chunk = new Buffer(chunk, encoding); + chunk = Buffer.from(chunk, encoding); return TestWriter.prototype._write.call(this, chunk, encoding, cb); }; @@ -191,7 +191,7 @@ test('write no bufferize', function(t) { chunks.forEach(function(chunk, i) { var enc = encodings[ i % encodings.length ]; - chunk = new Buffer(chunk); + chunk = Buffer.from(chunk); tw.write(chunk.toString(enc), enc); }); t.end(); @@ -235,7 +235,7 @@ test('end callback', function(t) { test('end callback with chunk', function(t) { var tw = new TestWriter(); - tw.end(new Buffer('hello world'), function() { + tw.end(Buffer.from('hello world'), function() { t.end(); }); }); @@ -249,7 +249,7 @@ test('end callback with chunk and encoding', function(t) { test('end callback after .write() call', function(t) { var tw = new TestWriter(); - tw.write(new Buffer('hello world')); + tw.write(Buffer.from('hello world')); tw.end(function() { t.end(); }); @@ -258,7 +258,7 @@ test('end callback after .write() call', function(t) { test('end callback called after write callback', function(t) { var tw = new TestWriter(); var writeCalledback = false; - tw.write(new Buffer('hello world'), function() { + tw.write(Buffer.from('hello world'), function() { writeCalledback = true; }); tw.end(function() { @@ -274,7 +274,7 @@ test('encoding should be ignored for buffers', function(t) { t.equal(chunk.toString('hex'), hex); t.end(); }; - var buf = new Buffer(hex, 'hex'); + var buf = Buffer.from(hex, 'hex'); tw.write(buf, 'binary'); }); @@ -335,7 +335,7 @@ test('dont end while writing', function(t) { assert(wrote); t.end(); }); - w.write(Buffer(0)); + w.write(Buffer.alloc(0)); w.end(); }); @@ -352,7 +352,7 @@ test('finish does not come before write cb', function(t) { assert(writeCb); t.end(); }); - w.write(Buffer(0)); + w.write(Buffer.alloc(0)); w.end(); }); @@ -366,7 +366,7 @@ test('finish does not come before sync _write cb', function(t) { assert(writeCb); t.end(); }); - w.write(Buffer(0), function(er) { + w.write(Buffer.alloc(0), function(er) { writeCb = true; }); w.end(); @@ -380,6 +380,6 @@ test('finish is emitted if last chunk is empty', function(t) { w.on('finish', function() { t.end(); }); - w.write(Buffer(1)); - w.end(Buffer(0)); + w.write(Buffer.allocUnsafe(1)); + w.end(Buffer.alloc(0)); }); diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js index 0aee70f6832c7f..64d25fefc94c86 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -24,10 +24,9 @@ r._read = function(n) { var totalPushed = 0; function push() { - var chunk = chunks-- > 0 ? new Buffer(chunkSize) : null; + var chunk = chunks-- > 0 ? Buffer.alloc(chunkSize, 'x') : null; if (chunk) { totalPushed += chunk.length; - chunk.fill('x'); } r.push(chunk); } diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js index a064250dcdd39f..e13ddcb167f662 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -9,7 +9,7 @@ var SD = require('string_decoder').StringDecoder; var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; var bufs = [ '☃💩', 'asdf' ].map(function(b) { - return new Buffer(b); + return Buffer.from(b); }); // also test just arbitrary bytes from 0-15. @@ -17,7 +17,7 @@ for (var i = 1; i <= 16; i++) { var bytes = new Array(i).join('.').split('.').map(function(_, j) { return j + 0x78; }); - bufs.push(new Buffer(bytes)); + bufs.push(Buffer.from(bytes)); } encodings.forEach(testEncoding); diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index 9d0034e2fc9c7d..39f80db9efa33f 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -6,10 +6,10 @@ var StringDecoder = require('string_decoder').StringDecoder; process.stdout.write('scanning '); // UTF-8 -test('utf-8', new Buffer('$', 'utf-8'), '$'); -test('utf-8', new Buffer('¢', 'utf-8'), '¢'); -test('utf-8', new Buffer('€', 'utf-8'), '€'); -test('utf-8', new Buffer('𤭢', 'utf-8'), '𤭢'); +test('utf-8', Buffer.from('$', 'utf-8'), '$'); +test('utf-8', Buffer.from('¢', 'utf-8'), '¢'); +test('utf-8', Buffer.from('€', 'utf-8'), '€'); +test('utf-8', Buffer.from('𤭢', 'utf-8'), '𤭢'); // A mixed ascii and non-ascii string // Test stolen from deps/v8/test/cctest/test-strings.cc // U+02E4 -> CB A4 @@ -19,15 +19,15 @@ test('utf-8', new Buffer('𤭢', 'utf-8'), '𤭢'); // U+3045 -> E3 81 85 test( 'utf-8', - new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]), + Buffer.from([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]), '\u02e4\u0064\u12e4\u0030\u3045' ); // UCS-2 -test('ucs2', new Buffer('ababc', 'ucs2'), 'ababc'); +test('ucs2', Buffer.from('ababc', 'ucs2'), 'ababc'); // UTF-16LE -test('ucs2', new Buffer('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up +test('ucs2', Buffer.from('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up console.log(' crayon!'); @@ -96,4 +96,3 @@ function writeSequences(length, start, sequence) { } return sequences; } - diff --git a/test/parallel/test-stringbytes-external-at-max.js b/test/parallel/test-stringbytes-external-at-max.js index 5c6455e808f217..624a94a63c4286 100644 --- a/test/parallel/test-stringbytes-external-at-max.js +++ b/test/parallel/test-stringbytes-external-at-max.js @@ -17,9 +17,9 @@ if (!common.enoughTestMem) { assert(typeof gc === 'function', 'Run this test with --expose-gc'); try { - var buf = new Buffer(kStringMaxLength); + var buf = Buffer.allocUnsafe(kStringMaxLength); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index f9bd78378e3414..68332232171ab4 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -10,7 +10,7 @@ var write_str = 'a'; // first do basic checks -var b = new Buffer(write_str, 'ucs2'); +var b = Buffer.from(write_str, 'ucs2'); var c = b.toString('binary'); assert.equal(b[0], 0x61); assert.equal(b[1], 0); @@ -22,7 +22,7 @@ write_str = Array(size).join(write_str); ucs2_control = Array(size).join(ucs2_control); // check resultant buffer and output string -b = new Buffer(write_str, 'ucs2'); +b = Buffer.from(write_str, 'ucs2'); // check fist Buffer created from write string for (let i = 0; i < b.length; i += 2) { assert.equal(b[i], 0x61); @@ -34,8 +34,8 @@ var b_ucs = b.toString('ucs2'); // check control against external binary string assert.equal(ucs2_control, b_bin); // create buffer copy from external -var c_bin = new Buffer(b_bin, 'binary'); -var c_ucs = new Buffer(b_ucs, 'ucs2'); +var c_bin = Buffer.from(b_bin, 'binary'); +var c_ucs = Buffer.from(b_ucs, 'ucs2'); // make sure they're the same length assert.equal(c_bin.length, c_ucs.length); // make sure Buffers from externals are the same @@ -60,7 +60,7 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; var slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); var pumped_string = slice.toString('hex'); var pumped_string2 = slice2.toString('hex'); - var decoded = new Buffer(pumped_string, 'hex'); + var decoded = Buffer.from(pumped_string, 'hex'); // the string are the same? for (var k = 0; k < pumped_string.length; ++k) { @@ -81,7 +81,7 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; var slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); var pumped_string = slice.toString('base64'); var pumped_string2 = slice2.toString('base64'); - var decoded = new Buffer(pumped_string, 'base64'); + var decoded = Buffer.from(pumped_string, 'base64'); // the string are the same? for (var k = 0; k < pumped_string.length - 3; ++k) { @@ -98,8 +98,8 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; // https://github.com/nodejs/node/issues/1024 (function() { var a = Array(1 << 20).join('x'); - var b = Buffer(a, 'ucs2').toString('ucs2'); - var c = Buffer(b, 'utf8').toString('utf8'); + var b = Buffer.from(a, 'ucs2').toString('ucs2'); + var c = Buffer.from(b, 'utf8').toString('utf8'); assert.equal(a.length, b.length); assert.equal(b.length, c.length); diff --git a/test/parallel/test-tls-alert-handling.js b/test/parallel/test-tls-alert-handling.js index 5e63384b0026f1..8c986b25f5e68d 100644 --- a/test/parallel/test-tls-alert-handling.js +++ b/test/parallel/test-tls-alert-handling.js @@ -71,7 +71,7 @@ function sendClient() { function sendBADTLSRecord() { - var BAD_RECORD = new Buffer([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + var BAD_RECORD = Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); var socket = net.connect(common.PORT); var client = tls.connect({ socket: socket, diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index 6e546600b68f6c..45e757e7a3c624 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -41,7 +41,7 @@ function test(cert, key, cb) { var completed = false; test(cert, key, function() { - test(new Buffer(cert), new Buffer(key), function() { + test(Buffer.from(cert), Buffer.from(key), function() { completed = true; }); }); diff --git a/test/parallel/test-tls-client-destroy-soon.js b/test/parallel/test-tls-client-destroy-soon.js index 554ac686dbdfbe..a8452904746f28 100644 --- a/test/parallel/test-tls-client-destroy-soon.js +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -19,12 +19,10 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; -var big = new Buffer(2 * 1024 * 1024); +var big = Buffer.alloc(2 * 1024 * 1024, 'Y'); var connections = 0; var bytesRead = 0; -big.fill('Y'); - // create server var server = tls.createServer(options, function(socket) { socket.end(big); diff --git a/test/parallel/test-tls-delayed-attach-error.js b/test/parallel/test-tls-delayed-attach-error.js index aec76d11b5628a..ca2562f683d7a0 100644 --- a/test/parallel/test-tls-delayed-attach-error.js +++ b/test/parallel/test-tls-delayed-attach-error.js @@ -10,8 +10,7 @@ var tls = require('tls'); var fs = require('fs'); var net = require('net'); -var bonkers = new Buffer(1024); -bonkers.fill(42); +var bonkers = Buffer.alloc(1024, 42); var receivedError = false; var options = { diff --git a/test/parallel/test-tls-fast-writing.js b/test/parallel/test-tls-fast-writing.js index 2a0130c162228d..e7cabd6d9a3943 100644 --- a/test/parallel/test-tls-fast-writing.js +++ b/test/parallel/test-tls-fast-writing.js @@ -42,8 +42,7 @@ function onconnection(conn) { } server.listen(PORT, function() { - var chunk = new Buffer(1024); - chunk.fill('x'); + var chunk = Buffer.alloc(1024, 'x'); var opt = { port: PORT, rejectUnauthorized: false }; var conn = tls.connect(opt, function() { conn.on('drain', ondrain); diff --git a/test/parallel/test-tls-hello-parser-failure.js b/test/parallel/test-tls-hello-parser-failure.js index 3378583af220f2..ecfbb9a70e4df9 100644 --- a/test/parallel/test-tls-hello-parser-failure.js +++ b/test/parallel/test-tls-hello-parser-failure.js @@ -16,8 +16,7 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem') }; -var bonkers = new Buffer(1024 * 1024); -bonkers.fill(42); +var bonkers = Buffer.alloc(1024 * 1024, 42); var server = tls.createServer(options, function(c) { diff --git a/test/parallel/test-tls-inception.js b/test/parallel/test-tls-inception.js index 8946f52bdd63d4..6f71e4682c2d84 100644 --- a/test/parallel/test-tls-inception.js +++ b/test/parallel/test-tls-inception.js @@ -14,7 +14,7 @@ var net = require('net'); var options, a, b; -var body = new Buffer(400000).fill('A'); +var body = Buffer.alloc(400000, 'A'); options = { key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), diff --git a/test/parallel/test-tls-max-send-fragment.js b/test/parallel/test-tls-max-send-fragment.js index 746994a69ca421..d52cb86bcf74f4 100644 --- a/test/parallel/test-tls-max-send-fragment.js +++ b/test/parallel/test-tls-max-send-fragment.js @@ -10,7 +10,7 @@ var tls = require('tls'); var fs = require('fs'); -var buf = new Buffer(10000); +var buf = Buffer.allocUnsafe(10000); var received = 0; var ended = 0; var maxChunk = 768; diff --git a/test/parallel/test-tls-ocsp-callback.js b/test/parallel/test-tls-ocsp-callback.js index e9443f45357995..27afb3431a48fc 100644 --- a/test/parallel/test-tls-ocsp-callback.js +++ b/test/parallel/test-tls-ocsp-callback.js @@ -68,7 +68,7 @@ function test(testOptions, cb) { // Just to check that async really works there setTimeout(function() { callback(null, - testOptions.response ? new Buffer(testOptions.response) : null); + testOptions.response ? Buffer.from(testOptions.response) : null); }, 100); }); server.listen(common.PORT, function() { diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js index a19c4aee403d87..6857773bb89008 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -39,7 +39,7 @@ server.listen(common.PORT, function() { send(); function send() { console.error('sending'); - var ret = client.write(new Buffer(bufSize)); + var ret = client.write(Buffer.allocUnsafe(bufSize)); console.error('write => %j', ret); if (false !== ret) { console.error('write again'); diff --git a/test/parallel/test-tty-wrap.js b/test/parallel/test-tty-wrap.js index 5e124dc89f7b87..6f94199c2b97a1 100644 --- a/test/parallel/test-tty-wrap.js +++ b/test/parallel/test-tty-wrap.js @@ -13,12 +13,12 @@ if (isTTY(1) == false) { var handle = new TTY(1); var callbacks = 0; -var req1 = handle.writeBuffer(Buffer('hello world\n')); +var req1 = handle.writeBuffer(Buffer.from('hello world\n')); req1.oncomplete = function() { callbacks++; }; -var req2 = handle.writeBuffer(Buffer('hello world\n')); +var req2 = handle.writeBuffer(Buffer.from('hello world\n')); req2.oncomplete = function() { callbacks++; }; diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js index 864361d80a6dfa..28ad67f6ef0ddd 100644 --- a/test/parallel/test-util.js +++ b/test/parallel/test-util.js @@ -73,7 +73,7 @@ assert.equal(true, util.isPrimitive(Symbol('symbol'))); // isBuffer assert.equal(false, util.isBuffer('foo')); -assert.equal(true, util.isBuffer(new Buffer('foo'))); +assert.equal(true, util.isBuffer(Buffer.from('foo'))); // _extend assert.deepEqual(util._extend({a:1}), {a:1}); diff --git a/test/parallel/test-zlib-dictionary-fail.js b/test/parallel/test-zlib-dictionary-fail.js index b4a344ceef5bb9..2c8939c68fac21 100644 --- a/test/parallel/test-zlib-dictionary-fail.js +++ b/test/parallel/test-zlib-dictionary-fail.js @@ -12,17 +12,17 @@ var zlib = require('zlib'); })); // String "test" encoded with dictionary "dict". - stream.write(Buffer([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); + stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); })(); // Should raise an error, not trigger an assertion in src/node_zlib.cc (function() { - var stream = zlib.createInflate({ dictionary: Buffer('fail') }); + var stream = zlib.createInflate({ dictionary: Buffer.from('fail') }); stream.on('error', common.mustCall(function(err) { assert(/Bad dictionary/.test(err.message)); })); // String "test" encoded with dictionary "dict". - stream.write(Buffer([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); + stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); })(); diff --git a/test/parallel/test-zlib-dictionary.js b/test/parallel/test-zlib-dictionary.js index 1a491c2ca1f261..2f3fc23a92d684 100644 --- a/test/parallel/test-zlib-dictionary.js +++ b/test/parallel/test-zlib-dictionary.js @@ -5,7 +5,7 @@ require('../common'); const assert = require('assert'); const zlib = require('zlib'); -const spdyDict = new Buffer([ +const spdyDict = Buffer.from([ 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-', 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi', 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser', diff --git a/test/parallel/test-zlib-flush-drain.js b/test/parallel/test-zlib-flush-drain.js index 14a42e76cc3874..9ec2f2a786dc56 100644 --- a/test/parallel/test-zlib-flush-drain.js +++ b/test/parallel/test-zlib-flush-drain.js @@ -3,7 +3,7 @@ require('../common'); const assert = require('assert'); const zlib = require('zlib'); -const bigData = new Buffer(10240).fill('x'); +const bigData = Buffer.alloc(10240, 'x'); const opts = { level: 0, diff --git a/test/parallel/test-zlib-flush.js b/test/parallel/test-zlib-flush.js index 69f734617e925e..69f218265bbb1b 100644 --- a/test/parallel/test-zlib-flush.js +++ b/test/parallel/test-zlib-flush.js @@ -11,9 +11,9 @@ const opts = { level: 0 }; const deflater = zlib.createDeflate(opts); const chunk = file.slice(0, chunkSize); -const expectedNone = new Buffer([0x78, 0x01]); -const blkhdr = new Buffer([0x00, 0x10, 0x00, 0xef, 0xff]); -const adler32 = new Buffer([0x00, 0x00, 0x00, 0xff, 0xff]); +const expectedNone = Buffer.from([0x78, 0x01]); +const blkhdr = Buffer.from([0x00, 0x10, 0x00, 0xef, 0xff]); +const adler32 = Buffer.from([0x00, 0x00, 0x00, 0xff, 0xff]); const expectedFull = Buffer.concat([blkhdr, chunk, adler32]); let actualNone; let actualFull; diff --git a/test/parallel/test-zlib-from-string.js b/test/parallel/test-zlib-from-string.js index 14c747fc433692..eadfa3d29a6c91 100644 --- a/test/parallel/test-zlib-from-string.js +++ b/test/parallel/test-zlib-from-string.js @@ -45,13 +45,13 @@ zlib.gzip(inputString, function(err, buffer) { }); }); -var buffer = new Buffer(expectedBase64Deflate, 'base64'); +var buffer = Buffer.from(expectedBase64Deflate, 'base64'); zlib.unzip(buffer, function(err, buffer) { assert.equal(buffer.toString(), inputString, 'decoded inflated string should match'); }); -buffer = new Buffer(expectedBase64Gzip, 'base64'); +buffer = Buffer.from(expectedBase64Gzip, 'base64'); zlib.unzip(buffer, function(err, buffer) { assert.equal(buffer.toString(), inputString, 'decoded gunzipped string should match'); diff --git a/test/parallel/test-zlib-params.js b/test/parallel/test-zlib-params.js index 4e02b7bdb9461c..db2d3879160f1e 100644 --- a/test/parallel/test-zlib-params.js +++ b/test/parallel/test-zlib-params.js @@ -12,7 +12,7 @@ const deflater = zlib.createDeflate(opts); const chunk1 = file.slice(0, chunkSize); const chunk2 = file.slice(chunkSize); -const blkhdr = new Buffer([0x00, 0x48, 0x82, 0xb7, 0x7d]); +const blkhdr = Buffer.from([0x00, 0x48, 0x82, 0xb7, 0x7d]); const expected = Buffer.concat([blkhdr, chunk2]); let actual; diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js index 4b28b3871800d1..c5d0adf2b4e2c4 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -78,7 +78,7 @@ RandomReadStream.prototype._process = function() { block += Math.ceil(Math.random() * jitter - (jitter / 2)); } block = Math.min(block, this._remaining); - var buf = new Buffer(block); + var buf = Buffer.allocUnsafe(block); for (var i = 0; i < block; i++) { buf[i] = Math.random() * 256; } diff --git a/test/parallel/test-zlib-zero-byte.js b/test/parallel/test-zlib-zero-byte.js index 826a9c7c79793d..677df17294a38e 100644 --- a/test/parallel/test-zlib-zero-byte.js +++ b/test/parallel/test-zlib-zero-byte.js @@ -4,7 +4,7 @@ var assert = require('assert'); var zlib = require('zlib'); var gz = zlib.Gzip(); -var emptyBuffer = new Buffer(0); +var emptyBuffer = Buffer.alloc(0); var received = 0; gz.on('data', function(c) { received += c.length; diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index 1256d94a61402d..261b519a6b0947 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -73,7 +73,7 @@ BufferStream.prototype.write = function(c) { BufferStream.prototype.end = function(c) { if (c) this.write(c); // flatten - var buf = new Buffer(this.length); + var buf = Buffer.allocUnsafe(this.length); var i = 0; this.chunks.forEach(function(c) { c.copy(buf, i); diff --git a/test/pummel/test-https-no-reader.js b/test/pummel/test-https-no-reader.js index d9d2b64cc73d62..72b558cf2dbedb 100644 --- a/test/pummel/test-https-no-reader.js +++ b/test/pummel/test-https-no-reader.js @@ -17,7 +17,7 @@ var options = { cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var buf = new Buffer(1024 * 1024); +var buf = Buffer.allocUnsafe(1024 * 1024); var server = https.createServer(options, function(req, res) { res.writeHead(200); diff --git a/test/pummel/test-regress-GH-814.js b/test/pummel/test-regress-GH-814.js index 820903d68873e7..031276efa602e2 100644 --- a/test/pummel/test-regress-GH-814.js +++ b/test/pummel/test-regress-GH-814.js @@ -2,7 +2,7 @@ // Flags: --expose_gc function newBuffer(size, value) { - var buffer = new Buffer(size); + var buffer = Buffer.allocUnsafe(size); while (size--) { buffer[size] = value; } @@ -39,7 +39,7 @@ var timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. if (PASS) { fs.write(testFileFD, newBuffer(kBufSize, 0x61), 0, kBufSize, -1, cb); gc(); - var nuBuf = new Buffer(kBufSize); + var nuBuf = Buffer.allocUnsafe(kBufSize); neverWrittenBuffer.copy(nuBuf); if (bufPool.push(nuBuf) > 100) { bufPool.length = 0; diff --git a/test/pummel/test-regress-GH-814_2.js b/test/pummel/test-regress-GH-814_2.js index d7c6d947919d59..c7a84b5ea67086 100644 --- a/test/pummel/test-regress-GH-814_2.js +++ b/test/pummel/test-regress-GH-814_2.js @@ -50,7 +50,7 @@ function writer() { gc(); gc(); gc(); - var nuBuf = new Buffer(kBufSize); + var nuBuf = Buffer.allocUnsafe(kBufSize); neverWrittenBuffer.copy(nuBuf); if (bufPool.push(nuBuf) > 100) { bufPool.length = 0; @@ -74,7 +74,7 @@ function writerCB(err, written) { function newBuffer(size, value) { - var buffer = new Buffer(size); + var buffer = Buffer.allocUnsafe(size); while (size--) { buffer[size] = value; } diff --git a/test/pummel/test-stream-pipe-multi.js b/test/pummel/test-stream-pipe-multi.js index 4524f8ca0b68c0..897b9d6dc27d46 100644 --- a/test/pummel/test-stream-pipe-multi.js +++ b/test/pummel/test-stream-pipe-multi.js @@ -10,7 +10,7 @@ var ww = []; var cnt = 100; var chunks = 1000; var chunkSize = 250; -var data = new Buffer(chunkSize); +var data = Buffer.allocUnsafe(chunkSize); var wclosed = 0; var rclosed = 0; diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 564a3f7f42d5a0..e03c49f13b9968 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -8,8 +8,7 @@ var EE = require('events').EventEmitter; function TestReader(n) { R.apply(this); - this._buffer = new Buffer(n || 100); - this._buffer.fill('x'); + this._buffer = Buffer.alloc(n || 100, 'x'); this._pos = 0; this._bufs = 10; } @@ -383,7 +382,7 @@ test('read(0) for ended streams', function(t) { var ended = false; r._read = function(n) {}; - r.push(new Buffer('foo')); + r.push(Buffer.from('foo')); r.push(null); var v = r.read(0); @@ -435,7 +434,7 @@ test('adding readable triggers data flow', function(t) { if (readCalled++ === 2) r.push(null); else - r.push(new Buffer('asdf')); + r.push(Buffer.from('asdf')); }; r.on('readable', function() { diff --git a/test/pummel/test-tls-server-large-request.js b/test/pummel/test-tls-server-large-request.js index cb740c63ed7d68..d15cb15c2ad8d8 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -14,7 +14,7 @@ var util = require('util'); var clientConnected = 0; var serverConnected = 0; -var request = new Buffer(new Array(1024 * 256).join('ABCD')); // 1mb +var request = Buffer.from(new Array(1024 * 256).join('ABCD')); // 1mb var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), diff --git a/test/sequential/test-buffer-bad-overload.js b/test/sequential/test-buffer-bad-overload.js index 2102c1f9a71d59..3d99dd532e9b93 100644 --- a/test/sequential/test-buffer-bad-overload.js +++ b/test/sequential/test-buffer-bad-overload.js @@ -3,13 +3,13 @@ require('../common'); const assert = require('assert'); assert.doesNotThrow(function() { - new Buffer(10); + Buffer.allocUnsafe(10); }); assert.throws(function() { - new Buffer(10, 'hex'); + Buffer.from(10, 'hex'); }); assert.doesNotThrow(function() { - new Buffer('deadbeaf', 'hex'); + Buffer.from('deadbeaf', 'hex'); }); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 6c7df10ffb09a7..b898eb89040b55 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -32,7 +32,7 @@ assert.throws(function() { }, /Command failed: iamabadcommand/); var msg = 'foobar'; -var msgBuf = new Buffer(msg + '\n'); +var msgBuf = Buffer.from(msg + '\n'); // console.log ends every line with just '\n', even on Windows. diff --git a/test/sequential/test-net-GH-5504.js b/test/sequential/test-net-GH-5504.js index 179b3ae3c2e241..0121f3bf25d1d7 100644 --- a/test/sequential/test-net-GH-5504.js +++ b/test/sequential/test-net-GH-5504.js @@ -19,8 +19,7 @@ switch (process.argv[2]) { function server() { var net = require('net'); - var content = new Buffer(64 * 1024 * 1024); - content.fill('#'); + var content = Buffer.alloc(64 * 1024 * 1024, '#'); net.createServer(function(socket) { this.close(); socket.on('end', function() { @@ -102,4 +101,3 @@ function parent() { }); } } - diff --git a/test/sequential/test-pipe.js b/test/sequential/test-pipe.js index c311a64d717833..36d40100a7fec6 100644 --- a/test/sequential/test-pipe.js +++ b/test/sequential/test-pipe.js @@ -16,7 +16,7 @@ var bufferSize = 5 * 1024 * 1024; /* * 5MB of random buffer. */ -var buffer = Buffer(bufferSize); +var buffer = Buffer.allocUnsafe(bufferSize); for (var i = 0; i < buffer.length; i++) { buffer[i] = parseInt(Math.random() * 10000) % 256; } @@ -108,4 +108,3 @@ process.on('exit', function() { assert.ok(gotThanks); assert.equal(bufferSize, tcpLengthSeen); }); - diff --git a/test/sequential/test-regress-GH-1697.js b/test/sequential/test-regress-GH-1697.js index bafd389fa8deee..1511cfd1cfcf6b 100644 --- a/test/sequential/test-regress-GH-1697.js +++ b/test/sequential/test-regress-GH-1697.js @@ -30,8 +30,8 @@ if (process.argv[2] === 'server') { serverProcess.stdout.once('data', function() { var client = net.createConnection(common.PORT, '127.0.0.1'); client.on('connect', function() { - const alot = new Buffer(1024); - const alittle = new Buffer(1); + const alot = Buffer.allocUnsafe(1024); + const alittle = Buffer.allocUnsafe(1); for (var i = 0; i < 100; i++) { client.write(alot); diff --git a/test/sequential/test-stringbytes-external-exceed-max-by-1-ascii.js b/test/sequential/test-stringbytes-external-exceed-max-by-1-ascii.js index 1e434d53b3d26e..058bc435fc8a96 100644 --- a/test/sequential/test-stringbytes-external-exceed-max-by-1-ascii.js +++ b/test/sequential/test-stringbytes-external-exceed-max-by-1-ascii.js @@ -17,9 +17,9 @@ assert(typeof gc === 'function', 'Run this test with --expose-gc'); const kStringMaxLength = process.binding('buffer').kStringMaxLength; try { - var buf = new Buffer(kStringMaxLength + 1); + var buf = Buffer.allocUnsafe(kStringMaxLength + 1); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/sequential/test-stringbytes-external-exceed-max-by-1-base64.js b/test/sequential/test-stringbytes-external-exceed-max-by-1-base64.js index ee3a64f5a0c87b..cc65206b4e448e 100644 --- a/test/sequential/test-stringbytes-external-exceed-max-by-1-base64.js +++ b/test/sequential/test-stringbytes-external-exceed-max-by-1-base64.js @@ -17,9 +17,9 @@ assert(typeof gc === 'function', 'Run this test with --expose-gc'); const kStringMaxLength = process.binding('buffer').kStringMaxLength; try { - var buf = new Buffer(kStringMaxLength + 1); + var buf = Buffer.allocUnsafe(kStringMaxLength + 1); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/sequential/test-stringbytes-external-exceed-max-by-1-binary.js b/test/sequential/test-stringbytes-external-exceed-max-by-1-binary.js index 0213140a5fe5e3..8689745528f93c 100644 --- a/test/sequential/test-stringbytes-external-exceed-max-by-1-binary.js +++ b/test/sequential/test-stringbytes-external-exceed-max-by-1-binary.js @@ -17,9 +17,9 @@ assert(typeof gc === 'function', 'Run this test with --expose-gc'); const kStringMaxLength = process.binding('buffer').kStringMaxLength; try { - var buf = new Buffer(kStringMaxLength + 1); + var buf = Buffer.allocUnsafe(kStringMaxLength + 1); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/sequential/test-stringbytes-external-exceed-max-by-1-hex.js b/test/sequential/test-stringbytes-external-exceed-max-by-1-hex.js index 5ad8de9ccf6941..0ec46fd6869e54 100644 --- a/test/sequential/test-stringbytes-external-exceed-max-by-1-hex.js +++ b/test/sequential/test-stringbytes-external-exceed-max-by-1-hex.js @@ -17,9 +17,9 @@ assert(typeof gc === 'function', 'Run this test with --expose-gc'); const kStringMaxLength = process.binding('buffer').kStringMaxLength; try { - var buf = new Buffer(kStringMaxLength + 1); + var buf = Buffer.allocUnsafe(kStringMaxLength + 1); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/sequential/test-stringbytes-external-exceed-max-by-1-utf8.js b/test/sequential/test-stringbytes-external-exceed-max-by-1-utf8.js index 6d7556578189fd..4ea46a2cc27189 100644 --- a/test/sequential/test-stringbytes-external-exceed-max-by-1-utf8.js +++ b/test/sequential/test-stringbytes-external-exceed-max-by-1-utf8.js @@ -17,9 +17,9 @@ assert(typeof gc === 'function', 'Run this test with --expose-gc'); const kStringMaxLength = process.binding('buffer').kStringMaxLength; try { - var buf = new Buffer(kStringMaxLength + 1); + var buf = Buffer.allocUnsafe(kStringMaxLength + 1); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/sequential/test-stringbytes-external-exceed-max-by-2.js b/test/sequential/test-stringbytes-external-exceed-max-by-2.js index db21608637dfb2..a75b5059b944a1 100644 --- a/test/sequential/test-stringbytes-external-exceed-max-by-2.js +++ b/test/sequential/test-stringbytes-external-exceed-max-by-2.js @@ -17,9 +17,9 @@ assert(typeof gc === 'function', 'Run this test with --expose-gc'); const kStringMaxLength = process.binding('buffer').kStringMaxLength; try { - var buf = new Buffer(kStringMaxLength + 2); + var buf = Buffer.allocUnsafe(kStringMaxLength + 2); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/sequential/test-stringbytes-external-exceed-max.js b/test/sequential/test-stringbytes-external-exceed-max.js index cf9dc37ec72594..51c36c55215990 100644 --- a/test/sequential/test-stringbytes-external-exceed-max.js +++ b/test/sequential/test-stringbytes-external-exceed-max.js @@ -17,9 +17,9 @@ assert(typeof gc === 'function', 'Run this test with --expose-gc'); const kStringMaxLength = process.binding('buffer').kStringMaxLength; try { - var buf = new Buffer(kStringMaxLength * 2 + 2); + var buf = Buffer.allocUnsafe(kStringMaxLength * 2 + 2); // Try to allocate memory first then force gc so future allocations succeed. - new Buffer(2 * kStringMaxLength); + Buffer.allocUnsafe(2 * kStringMaxLength); gc(); } catch (e) { // If the exception is not due to memory confinement then rethrow it. diff --git a/test/sequential/test-zerolengthbufferbug.js b/test/sequential/test-zerolengthbufferbug.js index de36444180b1ec..88e66a8d85332d 100644 --- a/test/sequential/test-zerolengthbufferbug.js +++ b/test/sequential/test-zerolengthbufferbug.js @@ -6,7 +6,7 @@ var assert = require('assert'); var http = require('http'); var server = http.createServer(function(req, res) { - var buffer = new Buffer(0); + var buffer = Buffer.alloc(0); // FIXME: WTF gjslint want this? res.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': buffer.length});