0% found this document useful (0 votes)
6 views47 pages

3 NodeJS

web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views47 pages

3 NodeJS

web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NodeJS

Trang Hồng Sơn

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 an open source server environment.

- NodeJS is free.

- NodeJS runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.).

- NodeJS uses JavaScript on the server.

tranghongson@[Link] 4 / 47
Why NodeJS ?

- NodeJS eliminates the waiting, and simply continues with the next request.

- NodeJS runs single-threaded, non-blocking, asynchronously programming, which is


very memory efficient.

Hình: Comparison between request handling in NodeJS and a traditional server

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 generate dynamic page content.

- NodeJS can create, open, read, write, delete, and close files on the server.

- NodeJS can collect form data.

- NodeJS can add, delete, modify data in your database.

tranghongson@[Link] 9 / 47
Get Started

- Download and install NodeJS from [Link]

- Create a NodeJS file named "[Link]", and add the following code:

1 [Link] ( " Hello SonKK " ) ;

- 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.

1 $FOLDER_PATH$ > node helloworld . js

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.

1 var t = setInterval ( printHello , 2 0 0 0 ) ;


2 function printHello ( ) {
3 [Link] ( " Hello SonKK " ) ;
4 }

- 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

- The Buffer object provides a way of handling stream of binary data.

- 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

1 var buf = [Link] ( [ 1 0 , 2 0 , 3 0 , 4 0 , 5 0 ] ) ;


2 [Link] ( buf ) ; // Hexadecimal
3 [Link] ( [Link] ) ;
4 [Link] ( [Link] ( ) ) ; // Decimal

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.

1 var buf = [Link] ( 4 ) ;


2 [Link] 3 2 BE ( 2 1 4 7 4 8 3 6 4 7 ) ; // Decimal
3 [Link] ( buf ) ; // Hexadecimal
4 [Link] ( [Link] ) ;

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.

1 var fs = require ( ' fs ') ;

- Common use for the File System module: create files, update files, rename files,
delete files, read files.

tranghongson@[Link] 19 / 47
Create files

- The [Link]() method takes a "flag" as the second argument.


- If the flag is "w" for "writing", the specified file is opened for writing.
- If the file does not exist, an empty file is created.

1 var fs = require ( ' fs ') ;


2 [Link] ( '. / [Link] ', 'w ', function ( err ) {
3 if ( err ) throw err ;
4 [Link] ( ' File created ! ') ;
5 });

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.

1 var fs = require ( ' fs ') ;


2 [Link] ( '. / [Link] ', ' Hello content ! ', function ( err ) {
3 if ( err ) throw err ;
4 [Link] ( ' File updated ! ') ;
5 });

- The [Link]() method appends specified content to a file.


- If the file does not exist, the file will be created.

1 var fs = require ( ' fs ') ;


2 [Link] ( '. / [Link] ', ' Hello content ! ', function ( err ) {
3 if ( err ) throw err ;
4 [Link] ( ' File updated ! ') ;
5 });

tranghongson@[Link] 21 / 47
Rename files

- The [Link]() method renames the specified file.

1 var fs = require ( ' fs ') ;


2 [Link] ( '. / [Link] ', '. / [Link] ', function ( err ) {
3 if ( err ) throw err ;
4 [Link] ( ' File renamed ! ') ;
5 });

tranghongson@[Link] 22 / 47
Delete files

- The [Link]() method deletes the specified file.

1 var fs = require ( ' fs ') ;


2 [Link] ( '. / [Link] ', function ( err ) {
3 if ( err ) throw err ;
4 [Link] ( ' File deleted ! ') ;
5 });

tranghongson@[Link] 23 / 47
Read files

- The [Link]() method is used to read files.

1 var fs = require ( ' fs ') ;


2 [Link] ( '. / [Link] ', function ( err , data ) {
3 if ( err ) throw err ;
4 [Link] ( [Link] ( ) ) ;
5 });

- [Link] file

1 < html >


2 < body >
3 < h 1 > Hello SonKK ! < / h 1 >
4 < / body >
5 < / html >

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.

1 var http = require ( ' http ') ;

- 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.

1 var http = require ( ' http ') ;


2 // create a server object
3 http. createSe rver ( function ( req , res ) {
4 [Link] ( ' Hello World ! ') ; // write a response to the client
5 [Link] ( ) ; // end the response
6 } ) .listen ( 8 0 8 0 ) ; // the server object listens on port 8080

- 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.

1 var http = require ( ' http ') ;


2 http. createSe rver ( function ( req , res ) {
3 [Link] ( 2 0 0 , { ' Content - Type ': ' text / html ' } ) ;
4 [Link] ( ' <h1 > Hello World ! </ h1 > ') ;
5 [Link] ( ) ;
6 } ) .listen ( 8 0 8 0 ) ;

- 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.

1 var url = require ( ' url ') ;

- Parse an address with the [Link]() method, and it will return a URL object with
each part of the address as properties.

1 var url = require ( ' url ') ;


2 var addr = ' http :// localhost :8080/ [Link] ? year =2017& month =
february ';
3 var q = [Link] ( addr , true ) ;
4 [Link] ( [Link] ) ; // returns ' localhost :8080 '
5 [Link] ( [Link] ) ; // returns '/ [Link] '
6 [Link] ( [Link] ) ; // returns '? year =2017& month = february '
7 var qdata = [Link] ; // returns an object : { year : 2017 , month : '
february ' }
8 [Link] ( [Link] ) ; // returns ' february '

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 ') ;

4 http. createSe rver ( function ( req , res ) {

5 var addr = [Link] ;


6 var q = [Link] ( addr , true ) ;
7 var filename = " . " + [Link] ;
8 [Link] ( filename , function ( err , data ) {
9 if ( err ) {
10 [Link] ( 4 0 4 , { ' Content - Type ': ' text / html ' } ) ;
11 [Link] ( " 404 Not Found " ) ;
12 } else {
13 [Link] ( 2 0 0 , { ' Content - Type ': ' text / html ' } ) ;
14 [Link] ( data ) ;
15 [Link] ( ) ;
16 }
17 });
18 } ) .listen ( 8 0 8 0 ) ;
tranghongson@[Link] 31 / 47
URL module
- Create two html files and save them in the same folder as your [Link] files.

1 < ! – summer . html – >


2 < html > < body >
3 < h 1 > Summer < / h 1 >
4 < p > I love the sun ! < / p >
5 < / body > < / html >

7 < ! – winter . html – >


8 < html > < body >
9 < h 1 > Winter < / h 1 >
10 < p > I love the snow ! < / p >
11 < / body > < / html >

- 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] ( ) ;

- Use the emit() method to fire an event.


1 // Create an event handler
2 var myEventHandler = function ( ) {
3 [Link] ( 'I hear a scream ! ') ;
4 }
5 var events = require ( ' events ') ;
6 var eventEmitter = new [Link] ( ) ;
7 // Assign the event handler to an event
8 [Link] ( ' scream ', myEventHandler ) ;
9 // Fire the ' scream ' event
10 event Emitter. emit ( ' scream ') ;
tranghongson@[Link] 34 / 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] 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".

1 $PROJECT_PATH$ > npm install upper - case - - save

- 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.

1 $PROJECT_PATH$ / node_modules / upper - case

tranghongson@[Link] 38 / 47
Upper-case module

- Using a package: include the "upper-case" package the same way you include any
other module.

1 var http = require ( ' http ') ;


2 var uc = require ( ' upper - case ') ;
3 http. createSe rver ( function ( req , res ) {
4 [Link] ( 2 0 0 , { ' Content - Type ': ' text / html ' } ) ;
5 [Link] ( uc ( " Hello World ! " ) ) ;
6 [Link] ( ) ;
7 } ) .listen ( 8 0 8 0 ) ;

- 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.

- The Nodemailer module can be downloaded and installed using npm.

1 $PROJECT_PATH$ > npm install nodemailer - - save

- Use the require() method to include the Nodemailer module.

1 var nodemailer = require ( ' nodemailer ') ;

tranghongson@[Link] 41 / 47
Nodemailer module
- Use the username and password from your selected email provider to send an email.

1 var nodemailer = require ( ' nodemailer ') ;


2 var transporter = n o d e m a i l e r . c r e a t e T r a n s p o r t ( {
3 service : ' gmail ',
4 auth : { user : ' youremail@[Link] ', pass : ' yourpassword ' }
5 });
6 var mailOptions = {
7 from : ' y ou remail@[Link] ',
8 to : ' my fr iend@[Link] ',
9 subject : ' Sending Email using NodeJS ',
10 text : ' That was easy ! '
11 };
12 tran s p o r t e r .s e ndMail ( mailOptions , function ( err , result ) {
13 if ( err ) [Link] ( err ) ;
14 else [Link] ( ' Email sent : ' + [Link] ) ;
15 });

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.

- The following example creates a module that returns an adder object.

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.

1 var adder = require ( " . / [Link] " ) ;


2 [Link] ( [Link] 2 number ( 6 , 9 ) ) ;
3 [Link] ( [Link] 3 number ( 6 , 9 , 2 ) ) ;

- 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

You might also like