nodejs tutorial foor free download from academia

ranimarri 14 views 36 slides Jul 11, 2024
Slide 1
Slide 1 of 36
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36

About This Presentation

notes


Slide Content

NodeJS

REQUIRED TOOLS
•Browser: Chrome
https://www.google.com/chrome/browser/desktop/index.html
•NodeJS(current) 8.6
https://nodejs.org
•API tester: Postman(as pluginfor Chrome)
•IDE: JetbrainsWebstorm/ JetbrainsIntelliJIDEA
•MongoDBCommunityServer
https://www.mongodb.com/download-center#community
•Robo3T –MongoDBGUI Client
https://robomongo.org/download

NodeJS
•Node.js isa JavaScript runtimebuilton Chrome'sV8 JavaScript engine.
•Node.js usesanevent-driven, non-blockingI/O model thatmakesit
lightweightand efficient.
•Node.js' packageecosystem, npm, isthe largestecosystemof open source
librariesin the world.

Whereto host NodeJSapp?
•Amazon Web Services –FreeTier
https://aws.amazon.com/free/
•Google cloudplatform –freetrial
https://cloud.google.com/nodejs/
•Microsoft Azure–freetrial
https://docs.microsoft.com/en-us/nodejs/azure/?view=azure-node-2.0.0
•PrivateVPS / Hosting

CREATING NODEJS PROJECT
•Manually
npm init
•Webstorm:
File->New->Project

ADDING PACKAGES
•New node_modulesdirectorycreated
•Package.json:
{
"name":"my-first-app",
"version":"1.0.0",
"description":"Somedescription",
"main":"index.js",
"scripts":{
"test":"echo \"Error: no test specified\" && exit1"
},
"author":"Krzysztof Bzowski",
"license":"ISC",
"dependencies":{
"express":"^4.16.0"
}
}
TIP:
npm i –S <package_name>@<version>
npm i –S [email protected]
TIP:
npminstall
Willinstallallmisingdependencies

ADDING PACKAGES VIA WEBSTORM
•File -> Settings-> Languages& Frameworks-> Node.js and NPM

PREPARATIONS –SIMPLE VERSION!
•Directory structure
•Project root
•node_modules
•src
•public
•Api
•Files:
•server.js
•api/index.js
•Startingscript: package.json
{
[…]
"scripts": {
"test": "echo \"Error: no test specified\"&& exit1",
"start": "nodedist\server.js"
},
[…]
}

PREPARATIONS –CODING ASSISTANCE
•File -> Settings-> Languages & Frameworks | Node.js and npm

BABEL
The compiler for writing next generation JavaScript
npm i -D babel-cli
npm i -D babel-preset-env
Webstorm: Files-> Settings-> Tools -> File Watchers

RUNNING -WEBSTORM
•Run -> Edit configuration
Start Debug

Server Config
•Createfile config.js
constenv= process.env;
export constnodeEnv= env.Node_ENV|| 'development'
export default{
port: env.PORT|| 8080
};
EDITOR TRANSPILED BY BABEL
'usestrict';
Object.defineProperty(exports, "__esModule", {
value: true
});
varenv= process.env;
varnodeEnv= exports.nodeEnv= env.Node_ENV|| 'development';
exports.default= {
port: env.PORT|| 8080
};
//# sourceMappingURL=config.js.map

Server –server.js
import config, {nodeEnv} from "./config";
import http from 'http'
Coremodule
Localmodule
constserver= http.createServer();
server.listen(8080);
server.on('request', (req, res) => {
// Handle request
});
Event emiter object
Event callbackwith
parameters:
•Request
•Response

Server –server.js
import config, {nodeEnv} from "./config";
import http from 'http'
constserver= http.createServer();
server.listen(8080);
server.on('request', (req, res) => {
// Handle request
res.write('Hello HTTP!\n');
res.end();
});

Testing-Postman
Bookmark
Sendrequest
Requesttype
RESPONSE

Express.js
•CoreHTTP module ispowerfullbut with growingapplicationitwillbe very
hard to handle allrequests. ThisiswhyExpress framework(and many
more) werecreated
import config, {nodeEnv} from "./config";
import express from 'express'
constserver= express();
// Routing
server.get('/', (req, res) => {
res.send('Hello express');
});
server.listen(config.port, () => {
console.log('Express listeningon port ', config.port);
});

Express.js -routing
import config, {nodeEnv} from "./config";
import express from 'express'
constserver= express();
// Routing
server.get('/', (req, res) => {
res.send('Hello express');
});
server.get('/about', (req, res) => {
res.send('ThisisExpress Appon ' + config.port);
});
server.listen(config.port, () => {
console.log('Express listeningon port ', config.port);
});

Express.js –return file
import fsfrom "fs";
[…]
server.get('/about.html', (req, res) => {
fs.readFile('./public/about.html' , (err, data) => {
res.send(data.toString());
})
});
<!DOCTYPE html>
<htmllang="en">
<head>
<meta charset="UTF-8">
<title>About</title>
</head>
<body>
<h1>About</h1>
<p>ThisisExpress App!</p>
</body>
</html>
./public/about.html:

Express.js –menagestaticfiles
•No fsmodule
•No routing
[…]
server.use(express.static('public’));
[…]
./server.js:

Express.js -Routing
./api/index.js:
import express from 'express'
constrouter = express.Router();
router.get('/', (req, res) => {
res.send({data: []})
});
export defaultrouter;
./server.js:
import config, {nodeEnv} from "./config";
import apiRouterfrom './api'
import express from 'express'
constserver= express();
server.use('/api', apiRouter);
server.use(express.static('public'));
server.listen(config.port, () => {
console.log('Express listeningon port ', config.port);
});

REST
•Representational state transfer (REST) or RESTful web services
•GET == Read
•POST == Create
•PUT == Update
•PATCH == Modify(partially)
•DELETE = Remove

REST HTTP Methods
HTTP Verb CRUD
Entire Collection (e.g.
/collection)
Specific Item (e.g.
/collection/{id})
POST Create
201 (Created), 'Location' header
with link to /collection/{id}
containing new ID.
404 (Not Found), 409 (Conflict) if
resource already exists..
GET Read
200 (OK), list of customers. Use
pagination, sorting and filtering
to navigate big lists.
200 (OK), single customer. 404
(Not Found), if ID not found or
invalid.
PUT Update/Replace
405 (Method Not Allowed),
unless you want to
update/replace every resource
in the entire collection.
200 (OK) or 204 (No Content).
404 (Not Found), if ID not found
or invalid.
PATCH Update/Modify
405 (Method Not Allowed),
unless you want to modify the
collection itself.
200 (OK) or 204 (No Content).
404 (Not Found), if ID not found
or invalid.
DELETE Delete
405 (Method Not Allowed),
unless you want to delete the
whole collection—not often
desirable.
200 (OK). 404 (Not Found), if ID
not found or invalid.

Handling errors
[…]
router.get('/user/:id', (req, res) => {
if(req.params.id == 1){
res.send({
id: 1,
name: 'Krzysztof'
})
} else{
res.status(404).send({
error: 'usernot found'
})
}
});
[…]
./api/index.js:

POST
./api/index.js:
import bodyParserfrom 'body-parser’
[…]
constserver= express();
server.use(bodyParser.json());
[…]
./server.js:
router.post('/user', (req, res) => {
console.log(req.body);
res.send(req.body);
console.log(`Tryingto create${req.body.name}user.`);
});

POST
REQUEST BODY
RESPONSE BODY

MongoDB
•Runningserver
"c:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --dbpath=e:\MongoDB\
•TIP: Makeandesktop shortcutwith thiscommand!
Database storage
Some convenient path with write access
(i.e. homedirectory)

MongoDB

MongoDB
•Createdatabase

MongoDB
•Createcollectionwith exampledata
{
"name" : "Krzysztof",
"role" : "teacher"
}

MongoDB
•Browsedata

MongoDB–Access from NodeJS
•npm i -S mongodb
constenv= process.env;
export constnodeEnv= env.Node_ENV|| 'development';
export default{
mongoUri: 'mongodb://localhost:27017/ie2017NS' ,
port: env.PORT|| 8080
};
./config.js:

MongoDB–Access from NodeJS
import {MongoClient, ObjectID} from 'mongodb'
import assertfrom 'assert'
import configfrom '../config'
letmdb;
MongoClient.connect(config.mongoUri, (err, db) => {
assert.equal(null, err);
mdb= db;
});
constrouter = express.Router();
router.get('/user', (req, res) => {
letusers= {};
mdb.collection('User').find({}).toArray(function(err, docs) {
docs.forEach((doc) => {
users[doc._id] = doc;
});
res.send(users);
});
});

MongoDB–filterdata
router.get('/user/:userId', (req, res) => {
letusers= {};
mdb.collection('User')
.findOne({_id : ObjectID(req.params.userId)})
.then(user=> res.send(user))
.catch(console.error)
});

MongoDB–Insertingdocuments
router.post('/user', (req, res) => {
constname= req.body.name;
constrole = req.body.role;
mdb.collection('User').insertOne({
name, role
}).then(result=> {
res.send(result.insertedId)
})
});

MongoDB–Update document
router.put('/user/:userId', (req, res) => {
letuid= req.params.userId;
constrole = req.body.role;
mdb.collection('User').findOneAndUpdate(
{_id: ObjectID(uid)},
{
$set: {
role
}
},
{new: true}
).then(result=> {
if(result.ok=== 1) {
res.send('');
} else{
res.status(404).send({'Error': 'User not found'})
}
}).catch(err=> {
letg = 3;
})
});

MongoDB–Deletedocument
router.delete('/user/:userId', (req, res) => {
letuid= req.params.userId;
mdb.collection('User').deleteOne(
{_id: ObjectID(uid)}
).then(result=> {
if(result.deletedCount=== 0){
res.status(404).send({'Error': 'User not found'})
} else{
res.send('');
}
})
});
Tags