COMP 1842
Node.js server
Matt Prichard
Introduction
NoSQL recap from week 6
Npm recap from week 5
Node js server
Recap – NoSQL
Please read these articles !!!
Very useful for your final report.
https://www.sitepoint.com/sql-vs-nosql-differences/
https://www.sitepoint.com/sql-vs-nosql-choose/
Recap -Running Node locally
• For these examples I am running
the files from my G Drive
• You can install Node and npm on
your own machines, but I can’t
directly support that.
• In the labs locate and open the
Node.js command prompt
Install check
Type node –v and press enter,
this will give the current version
of node that is installed, do the
same with
npm –v
G Drive – new folder npmtest
Create test.js and save to the
new folder
Run node
Open the Node command prompt, navigate to where the file is
(using cd npmtest or “change directory to npmtest ”) and type node test.js
to get the following output.
Navigating folders
cd folder_name/ change directory
cd ../ back up a directory
Can chain together
cd folder1/folder2/folder3/
cd ../../../
cd / takes you to the root directory
Node
Node.js can be used to build different types of
applications such as command line applications, web
applications, real-time chat application, REST API server
etc.
However, it is mainly used to build network programs like
web servers, similar to PHP, Java, or ASP.NET.
Cont…
A common task for a web server can be to open a file on the server
and return the content to the client.
Here is how PHP or ASP handles a file request:
1. Sends the task to the computer's file system.
2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.
Cont…
Here is how Node.js handles a file request:
1. Sends the task to the computer's file system.
2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns
the content to the client.
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronous programming,
which is very memory efficient.
https://medium.com/@monuchaudhary/single-threaded-non-blocking-asynchronous-and-concurrent-nature
-of-javascript-a0d5483bcf4c
single-threaded, non-blocking, asynchronous
programming
JavaScript is a single-threaded language. This means it has one call stack
and one memory heap. It executes code in order and must finish
executing a piece code before moving onto the next. So if we print from
1 to 5 it will execute every line one by one and can’t execute all console
logs at once.
Here a function is making an ajax request to google.com, which is
blocking the process. If we execute this code in C, PHP or any other
language it will execute like this.
JavaScript is a non-blocking language, the Call Google function call
doesn’t stop our rest of the code executing and printing “Ended”
before fetching data from google.com, like this.
But how is JavaScript non-blocking when it only has one thread?
The answer is that these requests are performed by web APIs (C+
+ library in case of node) which has its own thread. This makes
https://medium.com/@monuchaudhary/single-threaded-non-blocking-asynchronous-and-concurrent-nature
concurrency possible in JavaScript.
-of-javascript-a0d5483bcf4c
What Can Node.js Do?
• Node.js can generate dynamic page content
• Node.js can collect form data
• Node.js can add, delete, modify data in your database
• Node.js files contain tasks that will be executed on certain events
• A typical event is someone trying to access a port on the server
• Node.js files must be initiated on the server before having any effect
• Node.js files have extension ".js"
An aside => Arrow functions
Arrow functions are one of the features introduced in the ES6
version of JavaScript. It allows you to create functions in a cleaner
way compared to regular functions. For example:
Arrow function syntax
• myFunction is the name of the function
• arg1, arg2, ...argN are the function arguments
• statement(s) is the function body
If the body has single statement or expression, you can write arrow
function as:
Further
reading
https://www.w3schools.com/Js/js_arrow_function.asp
https://www.freecodecamp.org/news/arrow-function-javascript-tutorial-how-to-decla
re-a-js-function-with-the-new-es6-syntax/
Create new file
In the ‘npmtest’ folder from week 5 create a new file >
server.js
Node.js web server
• To access web pages of any web application, you need a web server. The
web server will handle all the http requests for the web application e.g
• IIS is a web server for ASP.NET web applications.
• Apache is a web server for PHP or Java web applications.
• Node.js provides capabilities to create your own web server which will
handle HTTP requests asynchronously. You can use IIS or Apache to run
Node.js web applications but it is recommended to use Node.js web
server.
Create Node.js web server
Node.js has a built-in module called HTTP, which allows Node.js to
transfer data over the Hyper-Text Transfer Protocol (HTTP).
To include the HTTP module, use the require( ) method:
const 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:
Create Node.js web server 2
The function passed into the http.createServer() method, will be
executed when someone tries to access the computer on port
8080.
Run the server
cd to the directory containing your new file if not already there.
Then type node server.js
Control C to stop the server
Add an HTTP Header
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: Line 3 set response header, Line 4 set response
content.
Restart the server
Restart the server node server.js
Note I have a new file server1, yours can still be the same file
In your browser go to localhost:8080
Fuller example
node-server/server2.js
Handle HTTP Requests
The http.createServer() method includes request and
response parameters which are supplied by Node.js.
The request object can be used to get information about the
current HTTP request e.g., url, request header, and data.
The response object can be used to send a response for a
current HTTP request.
Detail view
Using if and else if. We can use the ‘url’ property of the request
object to check the url of the current request lines 3 and 10
Detail view 2
Again, req.url is used to check the url of the current request and based on
that it sends the response. To send a response, first it sets the response
header using writeHead() method and then writes a string as a response
body using write() method. Finally, Node.js web server sends the response
using end() method.
Sending JSON response
Inserting lines 20-24 shows how to serve a JSON response from the
Node.js web server. this way we can create a simple web server that
serves different responses. (see: JSON.stringify)
Lab task for this week (#5 of 6)
Implement the code from slide 20 onwards from this lecture on your G
Drive or on your own machine.
Submit a screen shot of the server running in the command line on
port 8080
Show the different responses in the browser via localhost:8080
Home, student, admin and data (the JSON response)
Write 200-250 words explaining your understanding of today’s work
?
sources
https://www.tutorialsteacher.com/nodejs/create-nodejs-web-server
https://www.tutorialspoint.com/nodejs/nodejs_response_object.htm
https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/
https://www.w3schools.com/nodejs/nodejs_http.asp