nodejs create buffer from string
To create a buffer from a string in Node.js, you can follow these steps:
- First, import the
Buffer
module by using therequire
keyword:
const Buffer = require('buffer');
- Next, declare a variable to store your string:
const str = 'Hello, world!';
- Then, create a new buffer by calling the
Buffer.from()
method, passing in your string and specifying the encoding (usually 'utf-8'):
const buffer = Buffer.from(str, 'utf-8');
- Finally, you can access and manipulate the buffer as needed. For example, you can retrieve the contents of the buffer by calling
buffer.toString()
:
const contents = buffer.toString();
That's it! You have successfully created a buffer from a string in Node.js. Remember to handle any errors that may occur during the process.