Overview
This guide explains how to migrate to safe constructor methods. The migration fixes the following deprecation warning:
The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead.
- (recommended)
Finding problematic bits of code using
Just run .
It will find all the potentially unsafe places in your own code (with some considerably unlikely
exceptions).
Finding problematic bits of code using Node.js 8
If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code:
- will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js.
- does the same thing, but only for deprecation warnings.
- will show more types of deprecation warnings. In particular, it will show the deprecation warning, even on Node.js 8.
You can set these flags using environment variables:
Finding problematic bits of code using linters
ESLint rules no-buffer-constructor
or
node/no-deprecated-api
also find calls to deprecated API. Those rules are included in some presets.
There is a drawback, though, that it doesn’t always
when is
overridden e.g. with a polyfill, so recommended is a combination of this and some other method
described above.
dgram module functions#
History
Version | Changes |
---|---|
v11.4.0 |
The option is supported. |
v8.7.0 |
The and options are supported now. |
v8.6.0 |
The option is supported. |
v0.11.13 |
Added in: v0.11.13 |
-
Available options are:
-
The family of socket. Must be either or .
Required. -
When will reuse the
address, even if another process has already bound a socket on it.
Default: . -
Setting to will
disable dual-stack support, i.e., binding to address won’t make
be bound. Default: . - Sets the socket value.
- Sets the socket value.
- Custom lookup function. Default: .
-
The family of socket. Must be either or .
- Attached as a listener for events. Optional.
- Returns:
Creates a object. Once the socket is created, calling
will instruct the socket to begin listening for datagram
messages. When and are not passed to the
method will bind the socket to the «all interfaces» address on a random port
(it does the right thing for both and sockets). The bound address
and port can be retrieved using and
.
Added in: v0.1.99
- Either or .
- Attached as a listener to events.
- Returns:
Creates a object of the specified .
Once the socket is created, calling will instruct the
socket to begin listening for datagram messages. When and are
not passed to the method will bind the socket to the «all
interfaces» address on a random port (it does the right thing for both
and sockets). The bound address and port can be retrieved using
and .
Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x
This is the recommended solution nowadays that would imply only minimal overhead.
The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ ). This means that these versions of Node.js will not receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible.
What you would do in this case is to convert all or calls to use or , in the following way:
- For , replace it with .
- For (or ), replace it with (or ).
- For all other combinations of arguments (these are much rarer), also replace with .
Note that is also faster on the current Node.js versions than
, which is what you would otherwise need to ensure zero-filling.
Enabling ESLint rule no-buffer-constructor
or
node/no-deprecated-api
is recommended to avoid accidental unsafe API usage.
There is also a
for automatically migrating constructors to or .
Note that it currently only works with cases where the arguments are literals or where the
constructor is invoked with two arguments.
If you currently support those older Node.js versions and dropping support for them is not possible, or if you support older branches of your packages, consider using
or on older branches, so people using those older branches will also receive
the fix. That way, you will eradicate potential issues caused by unguarded API usage and
your users will not observe a runtime deprecation warning when running your code on Node.js 10.
Comments
silverwind
added
the
buffer
label
Fishrock123
added
discuss
memory
labels
rvagg
mentioned this issue
Node.js Foundation Core Technical Committee (CTC) Meeting 2016-01-13
#4668
Closed
jasnell
added
the
ctc-agenda
label
This was referenced Jan 27, 2016
Node.js Foundation Core Technical Committee (CTC) Meeting 2016-01-27
#4901
Closed
Node.js Foundation Core Technical Committee (CTC) Meeting 2016-02-03
#5058
Closed
rvagg
mentioned this issue
Node.js Foundation Core Technical Committee (CTC) Meeting 2016-02-10
#5176
Closed
rksm
mentioned this issue
Uninitialized buffer in proxy
#8
Closed
rvagg
mentioned this issue
Node.js Foundation Core Technical Committee (CTC) Meeting 2016-02-17
#5274
Closed
rvagg
removed
the
ctc-agenda
label
jasnell
closed this
mihaidma
mentioned this issue
Added test for password as buffer. Update some dependencies.
#43
Merged
micaksica
mentioned this issue
Safely allocate attachment buffers in PouchDB/Node.js
#5531
Closed
ChALkeR
mentioned this issue
buffer: runtime-deprecate Buffer constructor
#7152
Closed
2 of 2 tasks complete
not-an-aardvark
mentioned this issue
buffer: discuss future direction of Buffer constructor API
#9531
Closed
brianloveswords
mentioned this issue
Same issue with 0.2.12. Expected version «>=6.0.0»
#17
Closed
andreek
mentioned this issue
Raw telegram event
#48
Merged
notslang
mentioned this issue
replace deprecated `new Buffer()`
#71
Merged
goto-bus-stop
added a commit
to goto-bus-stop/tus-js-client
that referenced
this issue
goto-bus-stop
mentioned this issue
fix buffer initialization in base64 encoding in node
#75
Closed
Acconut
added a commit
to tus/tus-js-client
that referenced
this issue
seishun
mentioned this issue
buffer: runtime-deprecate Buffer ctor by default
#15346
Closed
3 of 4 tasks complete
idandagan1
mentioned this issue
new Buffer() is deprecated and it’s unsafe.
#631
Closed
seishun
mentioned this issue
buffer: runtime-deprecate Buffer constructor everywhere by default
#21351
Open
4 of 4 tasks complete
christianbundy
mentioned this issue
Indirectly depends on vulnerable version of bl.
#529
Closed
shiftkey
mentioned this issue
enable rule to warn about Buffer constructor usage
#7197
Merged
ghost
mentioned this issue
ValueError: could not convert string to float: b’undefined’
#241
Closed
jharrilim
mentioned this issue
Remove safe-buffer, Update Supported Node Versions
#26
Closed
sam-github
mentioned this issue
What to do about Buffer?
#564
Open
Memory Usage Tuning#
For zlib-based streams
From , modified for Node.js usage:
The memory requirements for deflate are (in bytes):
That is: 128K for = 15 + 128K for = 8
(default values) plus a few kilobytes for small objects.
For example, to reduce the default memory requirements from 256K to 128K, the
options should be set to:
This will, however, generally degrade compression.
The memory requirements for inflate are (in bytes)
This is in addition to a single internal output slab buffer of size
, which defaults to 16K.
The speed of compression is affected most dramatically by the
setting. A higher level will result in better compression, but
will take longer to complete. A lower level will result in less
compression, but will be much faster.
In general, greater memory usage options will mean that Node.js has to make
fewer calls to because it will be able to process more data on
each operation. So, this is another factor that affects the
speed, at the cost of memory usage.
For Brotli-based streams
There are equivalents to the zlib options for Brotli-based streams, although
these options have different ranges than the zlib ones:
- zlib’s option matches Brotli’s option.
- zlib’s option matches Brotli’s option.
See for more details on Brotli-specific options.
Принтер Zebra TLP 2824 PLUS
TLP 2824 Настольный термо-/термотрансферный принтер для печати на этикетках и билетах, с большим числом дополнительных приспособлений.
Сферы применения:
- медицина;
- розничная торговля;
- этикетирования корреспонденции и почты в офисе;
- сфера гостиничного бизнеса, развлечений и услуг; и т.д.
Это настольный принтер с шириной печатаемой этикетки 60 мм, модификация TLP — прямая и термотрансферная печать, идеально подходит для создания этикеток и ярлыков с текстом, графикой и различными видами штрих кода. Прекрасно подходит для маркировки упаковки и продукции в торговле, складском учете и для офисных нужд.
Принтер Zebra TLP 2824 относится к числу немногих термо/термотрансферных принтеров, для замены печатающей головки в которых Вам не потребуется откручивать ни одного винта, ни одной гайки. Печатающая головка, закрепленная на верхней крышке принтера, откидывается вместе с ней. Таким отбразом, Вы получаете полный и удобный доступ к головке для ее обслуживания и замены.
Отличительные особенности:
- универсальность и превосходное качество печати по выгодной цене
- принтеры выполнены в компактном дизайне – это идеальное решение для настольной печати
Convenience Methods#
All of these take a , , ,
or string as the first argument, an optional second argument
to supply options to the classes and will call the supplied callback
with .
Every method has a counterpart, which accept the same arguments, but
without a callback.
Added in: v11.7.0
- | | | |
Added in: v11.7.0
- | | | |
Compress a chunk of data with .
Added in: v11.7.0
- | | | |
Added in: v11.7.0
- | | | |
Decompress a chunk of data with .
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.6.0 |
Added in: v0.6.0 |
- | | | |
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.11.12 |
Added in: v0.11.12 |
- | | | |
Compress a chunk of data with .
History
Version | Changes |
---|---|
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.6.0 |
Added in: v0.6.0 |
- | | | |
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.11.12 |
Added in: v0.11.12 |
- | | | |
Compress a chunk of data with .
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.6.0 |
Added in: v0.6.0 |
- | | | |
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.11.12 |
Added in: v0.11.12 |
- | | | |
Decompress a chunk of data with .
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.6.0 |
Added in: v0.6.0 |
- | | | |
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.11.12 |
Added in: v0.11.12 |
- | | | |
Compress a chunk of data with .
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.6.0 |
Added in: v0.6.0 |
- | | | |
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.11.12 |
Added in: v0.11.12 |
- | | | |
Decompress a chunk of data with .
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.6.0 |
Added in: v0.6.0 |
- | | | |
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.11.12 |
Added in: v0.11.12 |
- | | | |
Decompress a chunk of data with .
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.6.0 |
Added in: v0.6.0 |
- | | | |
History
Version | Changes |
---|---|
v9.4.0 |
The parameter can be an . |
v8.0.0 |
The parameter can be any or . |
v8.0.0 |
The parameter can be an now. |
v0.11.12 |
Added in: v0.11.12 |
- | | | |
Decompress a chunk of data with .
Compressing HTTP requests and responses#
The module can be used to implement support for the ,
and content-encoding mechanisms defined by
.
The HTTP header is used within an http request to identify
the compression encodings accepted by the client. The
header is used to identify the compression encodings actually applied to a
message.
The examples given below are drastically simplified to show the basic concept.
Using encoding can be expensive, and the results ought to be cached.
See for more information on the speed/memory/compression
tradeoffs involved in usage.
By default, the methods will throw an error when decompressing
truncated data. However, if it is known that the data is incomplete, or
the desire is to inspect only the beginning of a compressed file, it is
possible to suppress the default error handling by changing the flushing
method that is used to decompress the last chunk of input data:
This will not change the behavior in other error-throwing situations, e.g.
when the input data has an invalid format. Using this method, it will not be
possible to determine whether the input ended prematurely or lacks the
integrity checks, making it necessary to manually check that the
decompressed result is valid.
Regarding Buffer.allocUnsafe()
Be extra cautious when using :
- Don’t use it if you don’t have a good reason to
- e.g. you probably won’t ever see a performance difference for small buffers, in fact, those
might be even faster with , - if your code is not in the hot code path — you also probably won’t notice a difference,
- keep in mind that zero-filling minimizes the potential risks.
- e.g. you probably won’t ever see a performance difference for small buffers, in fact, those
- If you use it, make sure that you never return the buffer in a partially-filled state,
Errors in handling buffers allocated with could result in various issues,
ranged from undefined behavior of your code to sensitive data (user input, passwords, certs)
leaking to the remote attacker.
Note that the same applies to usage without zero-filling, depending on the Node.js
version (and lacking type checks also adds DoS to the list of potential problems).
Модификации товара
Сортировать по: цене
ВсеПрямая термопечатьТермотрансфернаяUSBRS_232LPTEthernetножлотокчасыEthernet модульотделитель
282P-101520-000текущая модификация
Принтер этикеток Zebra TLP2824 Plus 282P-101520-000
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL USB Internal 10/100 Ethernet
43 576 ₽
282P-101120-000
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL Serial USB
22 927 ₽
282P-101220-000
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL Parallel
38 090 ₽
282P-101121-040
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL Serial USB Dispenser (Peeler) 68MB Flash Real Time Clock
35 483 ₽
282P-101522-040
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL USB Internal 10/100 Ethernet Cutter 68MB Flash Real Time Clock
66 451 ₽
282P-201520-000
DT Printer LP2824 Plus; 203dpi EU and UK Cords EPL ZPL USB Internal 10/100 Ethernet
Снят с производства
282P-101122-040
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL Serial USB Cutter 68MB Flash Real Time Clock
54 179 ₽
282P-201121-040
Принтер Zebra DT LP2824 Plus; 203dpi, Serial, USB, Dispenser (Peeler), 68MB Flash, Real Time Clock
Снят с производства
282P-101521-040
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL USB Internal 10/100 Ethernet Dispenser (Peeler) 68MB Flash Real Time Clock
47 470 ₽
282P-101221-040
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL Parallel Dispenser (Peeler) 68MB Flash Real Time Clock
36 538 ₽
282P-101222-040
TT Printer TLP2824 Plus; 203dpi EU and UK Cords EPL ZPL Parallel Cutter 68MB Flash Real Time Clock
48 272 ₽
2824-21120-0001
Принтер Zebra LP 2824 S
Снят с производства
282P-201120-000
DT Printer LP2824 Plus; 203dpi EU and UK Cords EPL ZPL Serial USB
Снят с производства
Usage:
Creating Buffers:
There are a few ways to create new buffers:
This buffer is initialized and contains 8 bytes of zero.
This initializes the buffer to the contents of this array. Keep in mind that the contents of the array are integers representing bytes.
This initializes the buffer to a binary encoding of the first string as specified by the second argument (in this case, ). is by far the most common encoding used with Node.js, but also supports others. See for more details.
Writing to Buffers
Given that there is already a buffer created:
we can start writing strings to it:
The first argument to is the string to write to the buffer, and the second argument is the string encoding. It happens to default to utf-8 so this argument is extraneous.
returned 5. This means that we wrote to five bytes of the buffer. The fact that the string «Hello» is also 5 characters long is coincidental, since each character just happened to be 8 bits apiece. This is useful if you want to complete the message:
When has 3 arguments, the second argument indicates an offset, or the index of the buffer to start writing at.
Reading from Buffers:
toString:
Probably the most common way to read buffers is to use the method, since many buffers contain text:
Again, the first argument is the encoding. In this case, it can be seen that not the entire buffer was used! Luckily, because we know how many bytes we’ve written to the buffer, we can simply add more arguments to «stringify» the slice that’s actually interesting:
Individual octets:
You can also set individual bytes by using an array-like syntax:
In this example, I set the remaining bytes, by hand, such that they represent utf-8 encoded «!» and «1» characters.
More Fun With Buffers
Buffer.byteLength(string, encoding)
With this function, you can check the number of bytes required to encode a string with a given encoding (which defaults to utf-8). This length is not the same as string length, since many characters require more bytes to encode. For example:
The unicode snowman is only one character, but takes 3 entire bytes to encode!
buffer.length
This is the length of your buffer, and represents how much memory is allocated. It is not the same as the size of the buffer’s contents, since a buffer may be half-filled. For example:
In this example, the contents written to the buffer only consist of three groups (since they represent the single-character snowman), but the buffer’s length is still 16, as it was initialized.
buffer.copy(target, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
allows one to copy the contents of one buffer onto another. The first argument is the target buffer on which to copy the contents of , and the rest of the arguments allow for copying only a subsection of the source buffer to somewhere in the middle of the target buffer. For example:
In this example, I copied the «snowman» buffer, which contains a 3 byte long character, to the «frosty» buffer, to which I had written to the first 16 bytes. Because the snowman character is 3 bytes long, the result takes up 19 bytes of the buffer.
buffer.slice(start, end=buffer.length)
This method’s API is generally the same as that of , but with one very import difference: The slice is not a new buffer and merely references a subset of the memory space. Modifying the slice will also modify the original buffer! For example:
Now Frosty has been turned into a puddle of underscores. Bummer.
usage
The goal of this package is to provide a safe replacement for the node.js .
It’s a drop-in replacement for . You can use it by adding one line to
the top of your node.js modules:
var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer(, 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
usage
The goal of this package is to provide a safe replacement for the node.js .
It’s a drop-in replacement for . You can use it by adding one line to
the top of your node.js modules:
var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer(, 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
Характеристики
Интерфейс подключения | |
---|---|
Интерфейс подключения | USB, RS-232 (COM порт, Serial) |
Характеристики печати | |
---|---|
Метод печати | Термотрансферная |
Разрешение | 203 dpi |
Скорость печати | 102 мм/сек |
Длина печати | 990 мм |
Память ОЗУ | 8 мб |
Флеш память | 4 мб |
Опциональная память | 68 мб |
Датчики печати | Датчик «открыта крышка» , Наличия этикетки, Расстояния между этикетками |
Ширина печати, мм | 56 |
Характеристики расходных материалов | |
---|---|
Ширина материала | 25,4-60 мм |
Толщина материала | 0,075-0,18 мм |
Макс. диаметр рулона материала | 127 мм |
Внутренний диаметр рулона материала | 1 дюйм (25,4 мм); 1,5 дюйма (38,1 мм) |
Тип материала | Рулонная или фальцованная бумага, отрезная или беспрерывная, этикетки прямой термопечати с/без черных меток, бумага для бирок, рулонная бумага для квитанций, наручные браслеты |
Длина красящей ленты | 74 м |
Ширина красящей ленты | 33-57 мм |
Внутренний диаметр рулона красящей ленты | 0,5 дюйм (12,7 мм) |
Электрические параметры | |
---|---|
Входное напряжение | 100-240 В |
Физические характеристики | |
---|---|
Цвет | белый |
Габариты оборудования | 24,1 х 13,5 х 17,8 см |
Вес оборудования | 1,6 кг |
Шрифты и графика | |
---|---|
Штрих-кода | EAN-8, EAN-13, Code 39, Code 93, Logmars, Plessey, Code 128, Standard 2-of-5, Code 11, MSI, Codabar, UPC-A, UPC-E, PDF417, QR Code, Maxi Code, Data Matrix, Сodablock , Aztec, Code49, Micro PDF417 |
Графика | 16 встроенных расширяемых растровых шрифтов ZPL II, один встроенный расширяемый шрифт ZPL, Пять встроенных расширяемых шрифтов EPL2, |
Программное обеспечение | |
---|---|
Языки программирования | Direct Protocol (DP), ZSim (ZPL-II), ESim (EPL), ZBI 2.0 |
Программное обеспечение | Драйвер ZebraDesigner, ZebraDesigner Pro, ZebraDesigner, ZebraNet Bridge Enterprise, Утилиты настройки Zebra, Универсальный драйвер Zebra, ZBI-Developer, |
Условия эксплуатации | |
---|---|
Влажность | 10%-90% без конденсата |
Температура эксплуатации | от 5º до 41º C |
Температура хранения | от -40° до 60° С |
Гарантия и производитель | |
---|---|
Производитель | Zebra / Motorola / Symbol |
Страна производства | Китай |
Модель | TLP2824 Plus |
Комплект | блок питания |
Гарантия | 2 года |
Характеристики принтера | |
---|---|
Вид принтера | Настольный |
Дополнительно | |
---|---|
Другие параметры | для печати на текстильной ленте |
Why Buffers?
Pure JavaScript, while great with unicode-encoded strings, does not handle straight binary data very well. This is fine on the browser, where most data is in the form of strings. However, Node.js servers have to also deal with TCP streams and reading and writing to the filesystem, both of which make it necessary to deal with purely binary streams of data.
One way to handle this problem is to just use strings anyway, which is exactly what Node.js did at first. However, this approach is extremely problematic to work with; It’s slow, makes you work with an API designed for strings and not binary data, and has a tendency to break in strange and mysterious ways.
Don’t use binary strings. Use buffers instead!
Variant 3 — Manual detection, with safeguards
This is useful if you create instances in only a few places (e.g. one), or you have your own
wrapper around them.
This special case for creating empty buffers can be safely replaced with , which
returns the same result all the way down to Node.js 0.8.x.
Before:
After:
is optional.
Note that the before is required (for cases when argument is not
hard-coded) and is not caused by the deprecation of constructor — it’s exactly why the
constructor is deprecated. Ecosystem packages lacking this type-check caused numerous
security issues — situations when unsanitized user input could end up in the create
problems ranging from DoS to leaking sensitive information to the attacker from the process memory.
When argument is hardcoded (e.g. literal or ), the check can
be omitted.
Also, note that using TypeScript does not fix this problem for you — when libs written in
are used from JS, or when user input ends up there — it behaves exactly as pure JS, as
all type checks are translation-time only and are not present in the actual JS code which TS
compiles to.
For Node.js 0.10.x (and below) support:
Otherwise (Node.js ≥ 0.12.x):
FAQ
What is wrong with the constructor?
The constructor could be used to create a buffer in many different ways:
-
creates a of 42 bytes. Before Node.js 8, this buffer contained
arbitrary memory for performance reasons, which could include anything ranging from
program source code to passwords and encryption keys. -
creates a that contains the UTF-8-encoded version of
the string . A second argument could specify another encoding: for example,
could be used to convert a Base64 string into the original
sequence of bytes that it represents. - There are several other combinations of arguments.
This meant that in code like , it is not possible to tell
what exactly the contents of the generated buffer are without knowing the type of .
Sometimes, the value of comes from an external source. For example, this function
could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form:
Note that this code does not validate the type of :
- is expected to be a string. If this is the case, all goes well.
- is controlled by the client that sends the request.
- If is the number , the would be bytes:
- Before Node.js 8, the content would be uninitialized
- After Node.js 8, the content would be bytes with the value
Because of the missing type check, an attacker could intentionally send a number
as part of the request. Using this, they can either:
- Read uninitialized memory. This will leak passwords, encryption keys and other
kinds of sensitive information. (Information leak) - Force the program to allocate a large amount of memory. For example, when specifying
as the input value, each request will allocate 500MB of memory.
This can be used to either exhaust the memory available of a program completely
and make it crash, or slow it down significantly. (Denial of Service)
Both of these scenarios are considered serious security issues in a real-world
web server context.
When using instead, passing a number will always
throw an exception instead, giving a controlled behavior that can always be
handled by the program.
The constructor has been deprecated for a while. Is this really an issue?
Surveys of code in the ecosystem have shown that the constructor is still
widely used. This includes new code, and overall usage of such code has actually been
increasing.