SlideShare a Scribd company logo
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

PPTX
Nodejs buffers
PPTX
INT 222.pptx
PPTX
module node jsbhgnbgtyuikmnbvcfyum2.pptx
PPTX
Getting Input from User
PPTX
Unit-2 Getting Input from User.pptx
PDF
javascript objects
PDF
JavaScript for impatient programmers.pdf
PDF
mfvlkdfjvnfdiuibvdbvhfvbvcbbhdbbdjhbdgcf
Nodejs buffers
INT 222.pptx
module node jsbhgnbgtyuikmnbvcfyum2.pptx
Getting Input from User
Unit-2 Getting Input from User.pptx
javascript objects
JavaScript for impatient programmers.pdf
mfvlkdfjvnfdiuibvdbvhfvbvcbbhdbbdjhbdgcf

Similar to NodeJs Modules.pdf (20)

KEY
JavaScript Growing Up
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
PDF
Chapter 2: What's your type?
PDF
Nodejs - Should Ruby Developers Care?
PPT
Java Script Introduction
PPTX
Chapter 1 .pptx
PDF
NodeJS for Beginner
PDF
ES6: The Awesome Parts
ODP
Node js lecture
PPT
fundamentals of JavaScript for students.ppt
PPT
Basics of Javascript
PPTX
All of javascript
PPTX
Unit-3.pptx node js ppt documents semester-5
PPTX
File system node js
PPTX
Java script
PDF
JS class slides (2016)
PDF
CoffeeScript
PDF
JavaScript Interview Questions 2023
PDF
javascript teach
PDF
JSBootcamp_White
JavaScript Growing Up
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Chapter 2: What's your type?
Nodejs - Should Ruby Developers Care?
Java Script Introduction
Chapter 1 .pptx
NodeJS for Beginner
ES6: The Awesome Parts
Node js lecture
fundamentals of JavaScript for students.ppt
Basics of Javascript
All of javascript
Unit-3.pptx node js ppt documents semester-5
File system node js
Java script
JS class slides (2016)
CoffeeScript
JavaScript Interview Questions 2023
javascript teach
JSBootcamp_White
Ad

More from Bareen Shaikh (12)

PDF
Express Generator.pdf
PDF
Middleware.pdf
PDF
ExpressJS-Introduction.pdf
PDF
Express JS-Routingmethod.pdf
PPTX
FS_module_functions.pptx
PPTX
File System.pptx
PDF
Web Server.pdf
PDF
NPM.pdf
PDF
NodeJs Modules1.pdf
PDF
Introduction to Node JS2.pdf
PDF
Introduction to Node JS1.pdf
PDF
Introduction to Node JS.pdf
Express Generator.pdf
Middleware.pdf
ExpressJS-Introduction.pdf
Express JS-Routingmethod.pdf
FS_module_functions.pptx
File System.pptx
Web Server.pdf
NPM.pdf
NodeJs Modules1.pdf
Introduction to Node JS2.pdf
Introduction to Node JS1.pdf
Introduction to Node JS.pdf
Ad

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Cloud computing and distributed systems.
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Machine Learning_overview_presentation.pptx
PDF
cuic standard and advanced reporting.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Network Security Unit 5.pdf for BCA BBA.
Unlocking AI with Model Context Protocol (MCP)
Cloud computing and distributed systems.
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Per capita expenditure prediction using model stacking based on satellite ima...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
A comparative analysis of optical character recognition models for extracting...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Big Data Technologies - Introduction.pptx
Programs and apps: productivity, graphics, security and other tools
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Machine Learning_overview_presentation.pptx
cuic standard and advanced reporting.pdf

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.