So when making a new Buffer in nodejs there are some things to be aware of. There is making a new buffer with the new keyword and what result that gives compared to the other options available in late versions of node.js. In this post I will be going over in detail what the deal is with making a new buffer with the new keyword in nodejs, and why it is that you might want to not do that if you have the option to do so.
So in many code examples the Buffer constructor is used as a way to create a new Buffer.
In late versions of nodejs 8.x and later a buffer that is created this way will be initialized. That is that the byte values will all be set to zero, and will therefrom not contain any old data that was in memory some of which might be sensitive. In older versions of node before 8.x this was not the case.
In older versions of node before 8.x a Buffer that is created with the new keyword would return a buffer that is not initialized with zeros when created by calling the Buffer constructor with the new keyword.
If you want to create a new empty buffer then Buffer.alloc is generally a better choice compared to calling the Buffer constructor with the new keyword. Although the security concern has been addressed in nodejs 8.x, it is still helps to make things more clear. Generally there is the Buffer.alloc, and Buffer.allocUnsafe that helps to better represent what the approach is compared to using new Buffer.
There is then also the option of using Buffer.allocUnsafe as well, this results to a similar effect with new Buffer in versions of node before 8.x. When using it the reason why it is called unsafe is because old data in memory is not written over out of the box when it is used. However because of that it is a littler faster to get a blank buffer.
Then there are a number of ways to create a new buffer with some data it it right away such as using the Buffer.from method for example.
In this sub section I am just creating a new buffer from a string and the default encoding is utf8. It is also possible to set the encoding as well as create buffers from arrays and objects also. For more on the buffer from method check out my post on Buffer.from in which I get into this method in detail.