3 NodeJS
3 NodeJS
tranghongson@[Link]
tranghongson@[Link] 1 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 2 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 3 / 47
What is NodeJS ?
- NodeJS is free.
tranghongson@[Link] 4 / 47
Why NodeJS ?
- NodeJS eliminates the waiting, and simply continues with the next request.
tranghongson@[Link] 5 / 47
Processing model
- Traditional web servers
- NodeJS
tranghongson@[Link] 6 / 47
What is the Event Loop ?
tranghongson@[Link] 7 / 47
What is the Event Loop ?
- Heap: This is where all the memory allocation happens for your variables, that you
have defined in your program.
- Stack: This is where all your javascript code gets pushed and executed one by one as
the interpreter reads your program, and gets popped out once the execution is done. If
your statement is asynchronous: setTimeout, ajax(), promise, or click event, etc, then
that code gets removed from Main Stack and forwarded to Event table, this table is
responsible for moving your asynchronous code to callback/event queue after specified
time.
- Callback Queue: This is where your asynchronous code gets pushed to, and waits for
the execution.
- Event Loop: Then comes the Event Loop, which keeps running continuously and
checks the Main stack if it has any frames to execute, if not then it checks Callback
queue, if Callback queue has codes to execute then it pops the message from it to the
Main Stack for the execution.
- See more details in [1 ] [2 ]
1
moviescom, Call Stack & Event Loop, 2018, url:
[Link]
2
ChanhBlog, JavaScript: Tổng quan về engine, runtime, call stack, single-threaded, concurrency,
event loop, 2018, url: [Link]
runtime-call-stack-va-event-loop.
tranghongson@[Link] 8 / 47
What can NodeJS do ?
- NodeJS can create, open, read, write, delete, and close files on the server.
tranghongson@[Link] 9 / 47
Get Started
- Create a NodeJS file named "[Link]", and add the following code:
- NodeJS files must be initiated in the "Command Line Interface" program of your
computer, navigate to the folder that contains the file "[Link]", write "node
[Link]" and hit ENTER.
tranghongson@[Link] 10 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 11 / 47
__filename vs. __dirname
- __filename represents the absolute path to the file (included the file name)
containing the code that is being executed.
1 [Link] ( __filename ) ;
- __dirname represents the absolute path to the file (excluded the file name)
containing the code that is being executed.
1 [Link] ( __dirname ) ;
tranghongson@[Link] 12 / 47
setTimeout(cb,ms) vs. clearTimeout(t)
- The global function setTimeout(cb,ms) is used to run a callback function named
"cb" after a "ms" milisecond interval.
1 var t = setTimeout ( printHello , 2 0 0 0 ) ;
2 function printHello ( ) {
3 [Link] ( " Hello SonKK " ) ;
4 }
5 var t = setTimeout ( ( ) => printHelloWithName ( " SonKK " ) , 2 0 0 0 ) ;
6 function pri nt HelloWithName ( name ) {
7 [Link] ( " Hello " + name ) ;
8 }
- The global function clearTimeout(t) is used to stop a Timer created by the previous
setTimeout(cb,ms) function.
1 var t = setTimeout ( printHello , 2 0 0 0 ) ;
2 function printHello ( ) {
3 [Link] ( " Hello SonKK " ) ;
4 clearTimeout ( t ) ;
5 }
tranghongson@[Link] 13 / 47
setInterval(cb,ms) vs. clearInterval(t)
- The global function setInterval(cb,ms) is used to run a callback function named "cb"
repeatedly after a "ms" milisecond interval.
- The global function clearInterval(t) is used to stop a Timer created by the previous
setInterval(cb,ms) function.
1 var count = 0 ;
2 var t = setInterval ( printHello , 2 0 0 0 ) ;
3 function printHello ( ) {
4 [Link] ( " Hello SonKK " ) ;
5 if (++count = = 3 ) clearInterval ( t ) ;
6 }
tranghongson@[Link] 14 / 47
Buffer object
- Use the from() method to creates a Buffer object from an object (string/array).
1 var buf = [Link] ( " Hello SonKK " , " utf -8 " ) ;
2 [Link] ( buf ) ; // Hexadecimal
3 [Link] ( [Link] ) ;
4 [Link] ( [Link] ( ) ) ;
5 [Link] ( [Link] ( ) ) ; // Decimal value from ASCII character
tranghongson@[Link] 15 / 47
Buffer object
- Use the alloc() method to creates a Buffer object of the specified length and
writeInt32BE() method to writes a 32 bit integer.
tranghongson@[Link] 16 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 17 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 18 / 47
File System module
- The File System module allows you to work with the file system on your computer,
use the require() method to include the File System module.
- Common use for the File System module: create files, update files, rename files,
delete files, read files.
tranghongson@[Link] 19 / 47
Create files
tranghongson@[Link] 20 / 47
Update files
- The [Link]() method replaces the specified file and content if it exists.
- If the file does not exist, a new file, containing the specified content, will be created.
tranghongson@[Link] 21 / 47
Rename files
tranghongson@[Link] 22 / 47
Delete files
tranghongson@[Link] 23 / 47
Read files
- [Link] file
tranghongson@[Link] 24 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 25 / 47
HTTP module
- HTTP module allows NodeJS to transfer data over the Hyper Text Transfer Protocol
(HTTP), use the require() method to include the HTTP module.
- The HTTP module can create an HTTP server that listens to server ports and gives a
response back to the client, use the createServer() method to create an HTTP server.
- Browser: [Link]
tranghongson@[Link] 26 / 47
HTTP module
- If the response from the HTTP server is supposed to be displayed as HTML, you
should include an HTTP header with the correct content type.
- Browser: [Link]
tranghongson@[Link] 27 / 47
HTTP module
- Assume we have the following [Link] file, located in the same folder as NodeJS.
1 < html >
2 < body >
3 < h 1 > Hello SonKK ! < / h 1 >
4 < / body >
5 < / html >
- Create an HTTP server that reads the [Link] file, and return the content.
1 var http = require ( ' http ') ;
2 var fs = require ( ' fs ') ;
3 http. createSe rver ( function ( req , res ) {
4 [Link] ( '. / [Link] ', function ( err , data ) {
5 [Link] ( 2 0 0 , { ' Content - Type ': ' text / html ' } ) ;
6 [Link] ( data ) ;
7 [Link] ( ) ;
8 });
9 } ) .listen ( 8 0 8 0 ) ;
- Browser: [Link]
tranghongson@[Link] 28 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 29 / 47
URL module
- The URL module splits up a web address into readable parts, use the require()
method to include the URL module.
- Parse an address with the [Link]() method, and it will return a URL object with
each part of the address as properties.
tranghongson@[Link] 30 / 47
URL module
- Create an HTTP server that opens the requested file and returns the content to the
client. If anything goes wrong, throw a 404 error.
1 var http = require ( ' http ') ;
2 var url = require ( ' url ') ;
3 var fs = require ( ' fs ') ;
- Browser:
• [Link]
• [Link]
• [Link]
tranghongson@[Link] 32 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 33 / 47
Events module
- The Events module can create, fire, and listen for your own events; use the require()
method to include the Events module. In addition, all event properties and methods
are an instance of an EventEmitter object. To be able to access these properties and
methods, create an EventEmitter object.
1 var events = require ( ' events ') ;
2 var eventEmitter = new [Link] ( ) ;
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 35 / 47
NPM
- What is NPM ?
• NPM (originally short for Node Package Manager) is a package manager for
NodeJS packages, or modules if you like.
• [Link] hosts thousands of free packages to download and use.
• The NPM program is installed on your computer when you install NodeJS.
- What is a Package ?
• A package in NodeJS contains all the files you need for a module.
• Modules are JavaScript libraries you can include in your project.
tranghongson@[Link] 36 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 37 / 47
Upper-case module
- Download a package: open the command line interface and tell NPM to download
the package you want.
- For example, to download a package called "upper-case".
- NPM creates a folder named "node_modules", where the package will be placed. All
packages you install in the future will be placed in this folder.
tranghongson@[Link] 38 / 47
Upper-case module
- Using a package: include the "upper-case" package the same way you include any
other module.
- Browser: [Link]
tranghongson@[Link] 39 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 40 / 47
Nodemailer module
- The Nodemailer module makes it easy to send emails from your computer.
tranghongson@[Link] 41 / 47
Nodemailer module
- Use the username and password from your selected email provider to send an email.
tranghongson@[Link] 42 / 47
Nodemailer module
- To send an email to more than one receiver, add them to the "to" property of the
mailOptions object, separated by commas.
1 var mailOptions = {
2 from : ' y ou remail@[Link] ',
3 to : ' myfriend@[Link] , m yo th er f ri en d @g ma il . co m ',
4 subject : ' Sending Email using NodeJS ',
5 text : ' That was easy ! '
6 }
- To send HTML formatted text in your email, use the "html" property instead of the
"text" property.
1 var mailOptions = {
2 from : ' y ou remail@[Link] ',
3 to : ' my fr iend@[Link] ',
4 subject : ' Sending Email using NodeJS ',
5 html : ' <h1 > Welcome </ h1 > <p > That was easy ! </p > '
6 }
tranghongson@[Link] 43 / 47
Outline
1. Introduction
2. Global objects
3. Built-in modules
3.1 File System module
3.2 HTTP module
3.3 URL module
3.4 Events module
4. NPM modules
4.1 Upper-case module
4.2 Nodemailer module
5. Custom module
tranghongson@[Link] 44 / 47
Your own module
- You can create your own modules, and easily include them in your applications.
1 class Adder {
2 add 2 number ( a , b ) { return a + b ; }
3 add 3 number ( a , b , c ) { return a + b + c ; }
4 }
5 var adder = new Adder ( ) ;
6 [Link] = adder ;
- Use the "exports" keyword to make properties and methods available outside the
module file.
- Save the code above in a file called "[Link]"
tranghongson@[Link] 45 / 47
Your own module
- Now you can include and use the module in any of your [Link] files.
- Notice that we use "./" to locate the module, that means that the module is located
in the same folder as the [Link] file.
tranghongson@[Link] 46 / 47
References
1. [Link]/nodejs
2. [Link]/playlist?list=PLzrVYRai0riQXAXJL9rg62tBvwD0ltJn-
tranghongson@[Link] 47 / 47