Reputation: 873
I understand why I need to use Buffer.
But I'm not super clear about the actual use of buffer syntax.
in the example below,
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
fs.writeFileSync('receivedText', message);
buffer was used to make a delay before
const message = parsedBody.split('=')[1];
fs.writeFileSync('receivedText', message);
is excuted.
but syntax-wise it's bit strage for me.
What if I want to make an array of many things, like
let arr=[]
for (let i=0; i<10; i++){
arr.push('hi')
}
I'm pretty sure that I can't do simply like
Buffer.(
let arr=[]
for (let i=0; i<10; i++){
arr.push('hi')
}
)
It feels like an async function and await combination though, I believe there must be something behind the scene.
As a simple example answer for that, What should I do if I want to do for loop using Buffer?
Thank you in advance.
Upvotes: 1
Views: 2016
Reputation: 707178
Buffer is an object in nodejs that is used for holding binary data - the type of data that can't be held in a UTF-8 string. This might be things like videos or images or other binary data.
It's very much like a Javascript-native Uint8Array
, in fact, it is actually a Uint8Array
under the covers now though this wasn't always the case because Buffer likely existed in nodejs before Uint8Array
was available in Javascript.
Inside of the Buffer constructor is a call to Buffer.alloc()
which in all cases ends up doing a new FastBuffer(...)
and FastBuffer
is declared as this:
class FastBuffer extends Uint8Array {}
So, a nodejs Buffer object is a sub-class of Uint8Array with some new methods added.
A Buffer has nothing at all do do with asynchronous operations except that some asynchronous operations such as fs.readFile()
produce a Buffer object as their output, but a Buffer itself has nothing at all to do with the timing of asynchronous operations.
Think of a Buffer like a special type of array that gives you byte level access to individual bytes of data, but instead of an array element which can hold any type of data, an individual element in a Buffer holds only a byte of data and thus the whole Buffer object holds something like an array of bytes of data.
You would use a Buffer object either when an API you call produces one or when you need to process data at the byte level or with binary values.
It feels like an async function and await combination though, I believe there must be something behind the scene.
Somewhere along the line, you got confused by something you saw. A buffer has nothing to do with async
or await
. It's just an object type that you can create yourself or you can use when some API returns one. It has a set of methods and properties as described here in the doc.
Upvotes: 4