Buffer is a temporary memory storage which stores the data when it is being moved from one place to another, it’s like the array of integers.
The Buffer.slice() method returns a new Buffer that points to the same memory location as that of the input Buffer with only the cropped elements.
Syntax:
buffer.slice( start, end )
Parameters: This method accepts two parameters as mentioned above and described below:
- start: It refers to the starting index from which the elements of input buffer will be copied to the output buffer.
- end: It refers to the ending index till which the elements of input buffer will be copied to the output buffer. (end index is not included in the count while slicing the buffer)
Return Value: It returns a buffer containing the altered buffer.
Note: Default value of start and end indexes are 0 and buffer.length respectively. Negative indexes start from end of the array.
Below examples illustrate the use of Buffer.slice() Method in Node.js:
Example 1:
// Node program to demonstrate the // Buffer.slice() method // Creating a buffer var buffer1 = new Buffer('GeeksForGeeks'); // Slicing a buffer var output = buffer1.slice(8, 12); // Converting the output buffer to string console.log("Sliced Buffer is: " + output.toString()); |
Output:
Sliced Buffer is: Geek
Example 2:
// Node program to demonstrate the // Buffer.slice() method const buffer = Buffer.from('Geek One'); const opBuffer = buffer.slice(0, 4) + " Two"; // Prints: Geek One console.log(buffer.toString()); // Prints: Geek Two console.log(opBuffer.toString()); |
Output:
Geek One Geek Two
Note: The above program will compile and run by using the node fileName.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end
Recommended Posts:
- Nodejs | Automatic restart NodeJs server with nodemon
- Nodejs console.timeLog() Method
- Nodejs | DNS
- Nodejs | Jimp
- Nodejs | DNS | setServers()
- Web-Socket in NodeJS
- Nodejs | GM equalize() Function
- Nodejs | GM whitePoint() Function
- Nodejs | GM magnify() Function
- Nodejs | GM minify() Function
- Nodejs | GM threshold() Function
- Nodejs | GM thumbnail() Function
- Nodejs | GM monochrome() Function
- Nodejs | GM motionBlur() Function
- Nodejs | GM write() Function
- Nodejs | GM whiteThreshold() Function
- Nodejs | GM modulate() Function
- Nodejs | GM drawRectangle() Function
- Nodejs | GM sharpen() Function
- Nodejs | GM blur() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

