SlideShare a Scribd company logo
1 of 17
Prepared By:
Prof. Bareen Shaikh
Department of Computer
Science,
MIT ACSC,ALNDI(D), PUNE
NodeJs Modules
Topics
 3.1 Functions
 3.2 Buffer
 3.3 Module and ModuleTypes
 3.4 Core Module, Local Module
 3.5 Directories as module
 3.5 Module. exports
Functions
 Functions are first class citizens in Node's JavaScript, similar to
the browser's JavaScript.
 A function can have attributes and properties also.
 It can be treated like a class in JavaScript.
Example:
function Sum(x,y) {
console.log(x+y);
}
Sum(505,606);
Buffers
 Definition: Buffer is an object property on Node’s global object, which is heavily
used in Node to deal with streams of binary data. It is globally available.
 JavaScript is Unicode friendly.
 But not dealing with binary data.
 Binary data is needed while handling withTCP or file system.
 For this NODEJS provide Buffer class.
 Buffer class store raw data similar as storing integer in array.
 But it will be stored at raw memory allocation outside of V8 heap.
 V8 is the default JavaScript engine which powers Node and Google Chrome
Creating Buffer
Following are the ways to create buffers:
 Buffer.from()
 Using constructor
 Buffer.alloc()
 Buffer.allocUnsafe()
Buffer.from()
 Buffer.from is used to create a buffer from either an array, a string, or
from a buffer itself.
 Buffer.from(‘Node.js’)
outputs <Buffer 4e 6f 64 65 2e 6a 73>
 Using Constructor
var buff=new Buffer(15);
var buff=new Buffer(“hello”);
Creating Buffer
 Buffer.alloc()
 Buffer.alloc takes a size (integer) as an argument and returns a new
initialized buffer of the specified size (i.e., it creates a filled buffer
of a certain size).
 >Buffer.alloc(8)
outputs <Buffer 00 00 00 00 00 00 00 00> //Here we have an 8-
byte buffer, and every bit is prefilled
with 0.
Creating Buffer
 Buffer.allocUnsafe()
 It takes in size as an argument and returns a new buffer that is non
initialized.
 It can contain some old or sensitive data out of your memory.
 This method is faster than the Buffer.alloc(), but use it carefully.
 >Buffer.allocUnsafe(8)
output <Buffer 18 cd 7e 02 00 00 00 00>
 We can see that there is some information left in our buffer
 In order to protect our sensitive information we need to prefill buffer
 Do that by using the fill() method.
 >Buffer.allocUnsafe(8).fill()
outputs <Buffer 00 00 00 00 00 00 00 00>
Reading from Buffer
 Syntax
buf.toString([encoding][, start][, end]) Parameters
 encoding − Encoding to use. 'utf8' is the default encoding.
 start − Beginning index to start reading, defaults to 0.
 end − End index to end reading, defaults is complete buffer.
 ReturnValue
This method decodes and returns a string from buffer data encoded
using the specified character set encoding.
Reading from Buffer Example
 > Buffer.from('Node.js')
<Buffer 4e 6f 64 65 2e 6a 73>
 > Buffer.from('Node.js').toString()
'Node.js'
 > Buffer.from('Node.js').toString('ascii')
'Node.js‘ //for 7-bitASCII data only
 > Buffer.from('Node.js').toString('utf8')
'Node.js‘ //multibyte encoded Unicode characters
 > Buffer.from('Node.js').toString('base64')
'Tm9kZS5qcw==‘ //Base64 encoding
 > Buffer.from('Node.js').toString('hex')
'4e6f64652e6a73‘ // encode each byte as two hexadecimal characters
Writing to a Buffer
 Syntax
buf.write(string[, offset][, length][, encoding]) Parameters
 string −This is the string data to be written to buffer.
 offset −This is the index of the buffer to start writing at. Default value
is 0.
 length −This is the number of bytes to write. Defaults to buffer.length.
 encoding − Encoding to use. 'utf8' is the default encoding.
 ReturnValue
This method returns the number of octets written. If there is not enough
space in the buffer to fit the entire string, it will write a part of the string.
 Example
buf = new Buffer(25);
len = buf.write(“HelloWorld“,”utf-8”);
console.log(“ written : "+ len);
Buffer example
 const str="bareen";
 > const buf=Buffer.from(str);
 > console.log('String Data',str)
OUTPUT : String Data bareen
 > console.log('String Data',str.length)
OUTPUT : String Data 6
 > console.log('String Data',buf)
OUTPUT : String Data <Buffer 62 61 72 65 65 6e>
 > console.log('String Data',buf.length)
OUTPUT : String Data 6
Buffer Functions
 Compare Buffers
buf.compare(otherBuffer);
 otherBuffer −This is the other buffer which will be compared
with buf
 ReturnValue
Returns a number indicating whether it comes before or after or is
the same as the otherBuffer in sort order.
 Example
Buffer Functions
 Compare Buffers Example
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1 +" comes before " + buffer2);
}
else if(result === 0) {
console.log(buffer1 +" is same as " + buffer2);
}
else {
console.log(buffer1 +" comes after " + buffer2);
}
Buffer Function
 Copying a Buffer
buf.copy(target[,target start[,sourcestart[,sourceend]]]);
 target −This is the target buffer in which to copy.
 target start- it is integer from where to start writing in buffer
 Source start-it is integer from which to begin copy in buffer
 Source end-it is integer where to stop copying in buffer
 ReturnValue
Returns a number indicating number bytes copied.
Buffer Functions
 Copying Buffers Example
var buffer1 = Buffer.allocUnsafe(26);
var buffer2 = Buffer. allocUnsafe(26).fill(‘!’);
console.log(buffer1.toString());
console.log(buffer1.toString());
for(let i=0;i<26;i++){
buffer1[i]=i+97;
}
buffer1.copy(buffer2,8,16,20);
console.log(buffer2.toString());
}
When to use Buffer
 Buffers are very useful when we need to read things like an image
from aTCP stream, a compressed file, or any other form of binary
data.
 Buffers are heavily used in streams in Node.
 Note:Just like arrays and strings, for buffer, we can use operations
like slice, indexOf, and many others.With some difference they are
to be used.
Thank You

More Related Content

Similar to NodeJs Modules.pdf

CSCI 2121- Computer Organization and Assembly Language Labor.docx
CSCI 2121- Computer Organization and Assembly Language Labor.docxCSCI 2121- Computer Organization and Assembly Language Labor.docx
CSCI 2121- Computer Organization and Assembly Language Labor.docxannettsparrow
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCKernel TLV
 
Dive into exploit development
Dive into exploit developmentDive into exploit development
Dive into exploit developmentPayampardaz
 
Ado.net session08
Ado.net session08Ado.net session08
Ado.net session08Niit Care
 
Berkeley Packet Filters
Berkeley Packet FiltersBerkeley Packet Filters
Berkeley Packet FiltersKernel TLV
 
INT 222.pptx
INT 222.pptxINT 222.pptx
INT 222.pptxSaunya2
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleHTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleKazuho Oku
 
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderAndrey Karpov
 
SO-Memoria.pdf
SO-Memoria.pdfSO-Memoria.pdf
SO-Memoria.pdfKadu37
 

Similar to NodeJs Modules.pdf (20)

CSCI 2121- Computer Organization and Assembly Language Labor.docx
CSCI 2121- Computer Organization and Assembly Language Labor.docxCSCI 2121- Computer Organization and Assembly Language Labor.docx
CSCI 2121- Computer Organization and Assembly Language Labor.docx
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Nio nio2
Nio nio2Nio nio2
Nio nio2
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Why learn Internals?
Why learn Internals?Why learn Internals?
Why learn Internals?
 
Nodejs buffers
Nodejs buffersNodejs buffers
Nodejs buffers
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
Dive into exploit development
Dive into exploit developmentDive into exploit development
Dive into exploit development
 
Bsdconv
BsdconvBsdconv
Bsdconv
 
Ado.net session08
Ado.net session08Ado.net session08
Ado.net session08
 
concurrency
concurrencyconcurrency
concurrency
 
Berkeley Packet Filters
Berkeley Packet FiltersBerkeley Packet Filters
Berkeley Packet Filters
 
INT 222.pptx
INT 222.pptxINT 222.pptx
INT 222.pptx
 
HTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS moduleHTTP::Parser::XS - writing a fast & secure XS module
HTTP::Parser::XS - writing a fast & secure XS module
 
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
SO-Memoria.pdf
SO-Memoria.pdfSO-Memoria.pdf
SO-Memoria.pdf
 

More from Bareen Shaikh

Express Generator.pdf
Express Generator.pdfExpress Generator.pdf
Express Generator.pdfBareen Shaikh
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfBareen Shaikh
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdfBareen Shaikh
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptxBareen Shaikh
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdfBareen Shaikh
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen Shaikh
 

More from Bareen Shaikh (11)

Express Generator.pdf
Express Generator.pdfExpress Generator.pdf
Express Generator.pdf
 
Middleware.pdf
Middleware.pdfMiddleware.pdf
Middleware.pdf
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdf
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdf
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptx
 
File System.pptx
File System.pptxFile System.pptx
File System.pptx
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
NPM.pdf
NPM.pdfNPM.pdf
NPM.pdf
 
NodeJs Modules1.pdf
NodeJs Modules1.pdfNodeJs Modules1.pdf
NodeJs Modules1.pdf
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdf
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

NodeJs Modules.pdf

  • 1. Prepared By: Prof. Bareen Shaikh Department of Computer Science, MIT ACSC,ALNDI(D), PUNE NodeJs Modules
  • 2. Topics  3.1 Functions  3.2 Buffer  3.3 Module and ModuleTypes  3.4 Core Module, Local Module  3.5 Directories as module  3.5 Module. exports
  • 3. Functions  Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript.  A function can have attributes and properties also.  It can be treated like a class in JavaScript. Example: function Sum(x,y) { console.log(x+y); } Sum(505,606);
  • 4. Buffers  Definition: Buffer is an object property on Node’s global object, which is heavily used in Node to deal with streams of binary data. It is globally available.  JavaScript is Unicode friendly.  But not dealing with binary data.  Binary data is needed while handling withTCP or file system.  For this NODEJS provide Buffer class.  Buffer class store raw data similar as storing integer in array.  But it will be stored at raw memory allocation outside of V8 heap.  V8 is the default JavaScript engine which powers Node and Google Chrome
  • 5. Creating Buffer Following are the ways to create buffers:  Buffer.from()  Using constructor  Buffer.alloc()  Buffer.allocUnsafe() Buffer.from()  Buffer.from is used to create a buffer from either an array, a string, or from a buffer itself.  Buffer.from(‘Node.js’) outputs <Buffer 4e 6f 64 65 2e 6a 73>  Using Constructor var buff=new Buffer(15); var buff=new Buffer(“hello”);
  • 6. Creating Buffer  Buffer.alloc()  Buffer.alloc takes a size (integer) as an argument and returns a new initialized buffer of the specified size (i.e., it creates a filled buffer of a certain size).  >Buffer.alloc(8) outputs <Buffer 00 00 00 00 00 00 00 00> //Here we have an 8- byte buffer, and every bit is prefilled with 0.
  • 7. Creating Buffer  Buffer.allocUnsafe()  It takes in size as an argument and returns a new buffer that is non initialized.  It can contain some old or sensitive data out of your memory.  This method is faster than the Buffer.alloc(), but use it carefully.  >Buffer.allocUnsafe(8) output <Buffer 18 cd 7e 02 00 00 00 00>  We can see that there is some information left in our buffer  In order to protect our sensitive information we need to prefill buffer  Do that by using the fill() method.  >Buffer.allocUnsafe(8).fill() outputs <Buffer 00 00 00 00 00 00 00 00>
  • 8. Reading from Buffer  Syntax buf.toString([encoding][, start][, end]) Parameters  encoding − Encoding to use. 'utf8' is the default encoding.  start − Beginning index to start reading, defaults to 0.  end − End index to end reading, defaults is complete buffer.  ReturnValue This method decodes and returns a string from buffer data encoded using the specified character set encoding.
  • 9. Reading from Buffer Example  > Buffer.from('Node.js') <Buffer 4e 6f 64 65 2e 6a 73>  > Buffer.from('Node.js').toString() 'Node.js'  > Buffer.from('Node.js').toString('ascii') 'Node.js‘ //for 7-bitASCII data only  > Buffer.from('Node.js').toString('utf8') 'Node.js‘ //multibyte encoded Unicode characters  > Buffer.from('Node.js').toString('base64') 'Tm9kZS5qcw==‘ //Base64 encoding  > Buffer.from('Node.js').toString('hex') '4e6f64652e6a73‘ // encode each byte as two hexadecimal characters
  • 10. Writing to a Buffer  Syntax buf.write(string[, offset][, length][, encoding]) Parameters  string −This is the string data to be written to buffer.  offset −This is the index of the buffer to start writing at. Default value is 0.  length −This is the number of bytes to write. Defaults to buffer.length.  encoding − Encoding to use. 'utf8' is the default encoding.  ReturnValue This method returns the number of octets written. If there is not enough space in the buffer to fit the entire string, it will write a part of the string.  Example buf = new Buffer(25); len = buf.write(“HelloWorld“,”utf-8”); console.log(“ written : "+ len);
  • 11. Buffer example  const str="bareen";  > const buf=Buffer.from(str);  > console.log('String Data',str) OUTPUT : String Data bareen  > console.log('String Data',str.length) OUTPUT : String Data 6  > console.log('String Data',buf) OUTPUT : String Data <Buffer 62 61 72 65 65 6e>  > console.log('String Data',buf.length) OUTPUT : String Data 6
  • 12. Buffer Functions  Compare Buffers buf.compare(otherBuffer);  otherBuffer −This is the other buffer which will be compared with buf  ReturnValue Returns a number indicating whether it comes before or after or is the same as the otherBuffer in sort order.  Example
  • 13. Buffer Functions  Compare Buffers Example var buffer1 = new Buffer('ABC'); var buffer2 = new Buffer('ABCD'); var result = buffer1.compare(buffer2); if(result < 0) { console.log(buffer1 +" comes before " + buffer2); } else if(result === 0) { console.log(buffer1 +" is same as " + buffer2); } else { console.log(buffer1 +" comes after " + buffer2); }
  • 14. Buffer Function  Copying a Buffer buf.copy(target[,target start[,sourcestart[,sourceend]]]);  target −This is the target buffer in which to copy.  target start- it is integer from where to start writing in buffer  Source start-it is integer from which to begin copy in buffer  Source end-it is integer where to stop copying in buffer  ReturnValue Returns a number indicating number bytes copied.
  • 15. Buffer Functions  Copying Buffers Example var buffer1 = Buffer.allocUnsafe(26); var buffer2 = Buffer. allocUnsafe(26).fill(‘!’); console.log(buffer1.toString()); console.log(buffer1.toString()); for(let i=0;i<26;i++){ buffer1[i]=i+97; } buffer1.copy(buffer2,8,16,20); console.log(buffer2.toString()); }
  • 16. When to use Buffer  Buffers are very useful when we need to read things like an image from aTCP stream, a compressed file, or any other form of binary data.  Buffers are heavily used in streams in Node.  Note:Just like arrays and strings, for buffer, we can use operations like slice, indexOf, and many others.With some difference they are to be used.