SlideShare a Scribd company logo
Node and SQLLite
SQLite Database with Node
https://www.udemy.com/node-
database/?couponCode=SLIDESHARE
INSTRUCTOR:
LAURENCE SVEKIS
Course instructor : Laurence Svekis
- Over 300 courses in technology and
web applications.
- 20 years of JavaScript web
programming experience
- 500,000+ students across multiple
platforms
- Digital instructor since 2002
READY TO HELP YOU LEARN and
ANSWER ANY questions you may
have.
Windows Terminal
Windows - https://cmder.net/ or use the
command prompt terminal
Launch the Command Prompt - use the Run
window or press the Win + R keys on your
keyboard. Then, type cmd and press Enter.
List current directory of files - dir
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Mac Terminal
Open Terminal by pressing Command+Space or
select terminal in the applications list.
List current directory of files - ls
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Command Line Launch
One node is installed check to see version
installed. Type node -v
Open your editor and create a js file that
contains console.log('Hello World'); save
it as test.js
In the terminal type node test.js and watch
for a result. What gets returned?
NPM - check if its installed npm -v latest
version install npm install npm@latest -g
Create app js file
Create a main app js file to run your node application.
touch app.js
Install setup Node and Express
https://nodejs.org/en/download/
Select the platform and install
Setup of Localhost machine
https://expressjs.com/
In the terminal
node -v
npm install express --save
Npm package.json
Install all the dependencies for your project. Create
a package.json file.
You can also install packages using
Optional flags
--save - installs and adds to the package.json
--save-dev - installs and adds to the package.json
under devDependencies.
Updating packages - check all packages or specific
package.
npm install <package-name>
npm update
npm update <package-name>
Npm install Packages
Default its installed under the current tree. Npm init
to create package.json
Also adds the dependencies to the package.json
file in current folder.
Global installations of the package can be done by
adding the flag -g. Will install package to global
location.
Get global root folder.
npm init
npm install -g <package-name>
npm root -g
Npm uninstall Packages
Default its installed under the current tree.
Also adds the dependencies to the package.json
file in current folder.
Global installations of the package can be done by
adding the flag -g. Will install package to global
location.
Get global root folder.
npm uninstall <package-name>
npm install -g <package-name>
npm root -g
Setup - Local Server
Run app.js and Open Browser to localhost:8080 -
port with http path.
Assign variable to app object.
Open http://localhost:8080/ in your browser.
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('ready')
})
app.listen(8080, function () {
console.log('Server ready')
})
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('ready')
})
const server = app.listen(8080, function () {
console.log('Server ready')
})
node app.js
NodeMon
Nodemon is a utility that will monitor for any
changes in your source and automatically restart
your server. Perfect for development.
npm install -g nodemon
https://nodemon.io/
Run it
nodemon app.js
** make some changes no more node restart
typing ;)
Setup - Local Express Server
Run app.js and Open Browser to localhost:8080 -
port with http path.
Assign variable to app object.
Open http://localhost:8080/ in your browser.
const express = require('express');
const app = express();
const port = 8080;
const server = app.listen(port, function () {
console.log('Server ready')
})
app.get('/', function (req, res) {
res.json({
"status": "ready"
})
})
app.use(function (req, res) {
res.status(404);
});
nodemon app.js
Install SQLlite and MD5 for hash of passwords
https://www.npmjs.com/package/sqlite3
SQLite is a relational database management
system contained in a C library. In contrast to
many other database management systems,
SQLite is not a client–server database engine.
Rather, it is embedded into the end program.
https://www.sqlite.org/about.html
npm install sqlite3
a JavaScript function for hashing messages with
MD5.
https://www.npmjs.com/package/md5
npm install md5
Setup - Database and create Table
Create a new js file to setup a database.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
db.run('CREATE TABLE users(id INTEGER PRIMARY KEY
AUTOINCREMENT,first,last,email,password)');
db.close();
touch dbsetup.js
mkdir db
node dbsetup.js
touch insert.js
touch insert.js
Create a new js file to insert to the database.
Add to database new users table.
Catch the errors
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
let sql = 'INSERT INTO users (first,last,email,password) VALUES
("Laurence", "Svekis", "gappscourses@gmail.com", "password")';
db.run(sql, [], function(err) {
if (err) {
return console.log(err.message);
}
console.log(`Rowid ${this.lastID}`);
});
db.close();
Database as module
Setup the db.js file as the database connection,
useful if you need to change file locations.
Use a module
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./db/user.db');
module.exports = db;
**** On app.js add
const db = require("./db.js")
touch db.js
Query Database for users
Querying all rows with all() method -
Will output all the contents of the database.
const sqlite3 = require('sqlite3').verbose();
const md5 = require('md5');
const db = new sqlite3.Database('./db/user.db');
module.exports = db;
**** On app.js add
const db = require("./db.js")
const db = require("./db.js")
const query = "select * from users";
db.all(query, function (err, rows) {
if (err) {
throw err;
}
rows.forEach(function (row) {
console.log(row);
});
});
List users in web page
Using express setup a new route for users const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
app.get('/users', function (req, res) {
const query = "select * from users";
db.all(query, function (err, rows) {
if (err) {
throw err;
}
res.json({
"data": rows
});
});
})
app.get('/', function (req, res) {
res.json({
"status": "ready"
})
})
app.use(function (req, res) {
res.status(404);
});
List get users by id
In the browser go to the users folder and add an
id value at the end.
app.get("/users/:id", function (req, res) {
const query = "select * from users where id = ?"
const params = [req.params.id]
db.get(query, params, function (err, row) {
if (err) {
throw err;
}
res.json({
"data": row
})
});
});
Create new User
Create the browser side add.html file with a form
for inputs and event listener to send request.
For node setup install of body-parser
https://github.com/expressjs/body-parser body
parsing middleware
<form>
<input type='text' name='first' value='Laurence'>
<input type='text' name='last' value='Svekis'>
<input type='text' name='email' value='example@example.com'>
<input type='text' name='password' value='secret'>
<input type='submit'> </form>
<script>
const myForm = document.querySelector('form');
const inputs = document.querySelectorAll('input');
myForm.addEventListener("submit", function (evt) {
evt.preventDefault();
fetch('/adder', {
method: 'POST'
, body: JSON.stringify({
first: inputs[0].value
, last: inputs[1].value
, email: inputs[2].value
, password: inputs[3].value
, })
, headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
return response.json()
}).then(function (body) {
console.log(body);
});
});
</script>
npm install body-parser
Node get new user data
Submit the form and check for request data from
the body in the console.
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.post('/adder', function (req, res) {
console.log(req.body);
console.log('req.body.first', req.body['first']);
})
Add new user to database
Update post to insert into database.
You can go to users to list all
http://localhost:8080/users
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.post('/adder', function (req, res) {
console.log(req.body);
let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)'
db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']],
function (err, row) {
if (err) {
throw err;
}
res.json({
"data": this.lastID
})
});
})
app.use(function (req, res) {
res.status(404);
});
Full Source Code app.js
app.get('/', function (req, res) {
res.json({"status": "ready"})
})
app.get('/new', function (req, res) {
res.sendFile(__dirname + '/add.html');
})
app.post('/adder', function (req, res) {
console.log(req.body);
let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)'
db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']],
function (err, row) {
if (err) {throw err;}
res.json({"data": this.lastID })
});
})
app.use(function (req, res) {
res.status(404);
});
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {console.log('Server ready')})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/users', function (req, res) {
const query = "select * from users";
const params = [];
db.all(query, params, function (err, rows) {
if (err) {throw err;}
res.json({"data": rows});
});
})
app.get("/users/:id", function (req, res) {
const query = "select * from users where id = ?"
const params = [req.params.id]
db.get(query, params, function (err, row) {
if (err) {throw err;}
res.json({ "data": row })
});
});
Full Source Code other files
<!-- add.html -->
<form><input type='text' name='first' value='Laurence'><input type='text' name='last'
value='Svekis'><input type='text' name='email' value='example@example.com'><input
type='text' name='password' value='secret'><input type='submit'> </form>
<script>
const myForm = document.querySelector('form');
const inputs = document.querySelectorAll('input');
myForm.addEventListener("submit", function (evt) {
evt.preventDefault();
fetch('/adder', {
method: 'POST'
, body: JSON.stringify({first: inputs[0].value, last: inputs[1].value, email:
inputs[2].value, password: inputs[3].value })
, headers: {"Content-Type": "application/json" }
}).then(function (response) {
return response.json()
}).then(function (body) {
console.log(body);
});
});
</script>
//db.js
const sqlite3 = require('sqlite3').verbose()
const md5 = require('md5')
const db = new sqlite3.Database('./db/user.db');
module.exports = db
//dbsetup.js
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
db.run('CREATE TABLE users(id INTEGER PRIMARY KEY
AUTOINCREMENT,first,last,email,password)');
db.close();
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis",
"gappscourses@gmail.com", "password")';
db.run(sql, [], function(err) {
if (err) {
return console.log(err.message);
}
console.log(`Rowid ${this.lastID}`);
});
db.close();
Congratulations on completing the section
Course instructor : Laurence Svekis -
providing online training to over
500,000 students across hundreds of
courses and many platforms.
Find out more about my courses at
http://www.discoveryvip.com/

More Related Content

What's hot (20)

PDF
jQuery - Chapter 3 - Effects
WebStackAcademy
 
PDF
JavaScript: Variables and Functions
Jussi Pohjolainen
 
PDF
Javascript
Vibhor Grover
 
PDF
Nodejs presentation
Arvind Devaraj
 
PPTX
jQuery PPT
Dominic Arrojado
 
PDF
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PDF
21 Essential JavaScript Interview Questions
Arc & Codementor
 
PPTX
Dom(document object model)
Partnered Health
 
PDF
Javascript basics
shreesenthil
 
PPTX
React hooks
Assaf Gannon
 
PPT
Javascript
mussawir20
 
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
PDF
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
PPTX
Unit iv
bhushan_adavi
 
PDF
Use Node.js to create a REST API
Fabien Vauchelles
 
PDF
Threads concept in java
Muthukumaran Subramanian
 
PDF
SEH overwrite and its exploitability
FFRI, Inc.
 
PPTX
ReactJs presentation
nishasowdri
 
jQuery - Chapter 3 - Effects
WebStackAcademy
 
JavaScript: Variables and Functions
Jussi Pohjolainen
 
Javascript
Vibhor Grover
 
Nodejs presentation
Arvind Devaraj
 
jQuery PPT
Dominic Arrojado
 
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
React + Redux Introduction
Nikolaus Graf
 
21 Essential JavaScript Interview Questions
Arc & Codementor
 
Dom(document object model)
Partnered Health
 
Javascript basics
shreesenthil
 
React hooks
Assaf Gannon
 
Javascript
mussawir20
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Unit iv
bhushan_adavi
 
Use Node.js to create a REST API
Fabien Vauchelles
 
Threads concept in java
Muthukumaran Subramanian
 
SEH overwrite and its exploitability
FFRI, Inc.
 
ReactJs presentation
nishasowdri
 

Similar to Local SQLite Database with Node for beginners (20)

PDF
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
PPTX
Introduction to node.js
Adrien Guéret
 
PPTX
NodeJS
Alok Guha
 
PPT
nodejs tutorial foor free download from academia
rani marri
 
PPTX
Introduction to Node.js
Winston Hsieh
 
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
PDF
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
KEY
Building a real life application in node js
fakedarren
 
PDF
Download full ebook of Learning Node Shelley Powers instant download pdf
zeitsloyerqy
 
PDF
Introduction to Node.js
Somkiat Puisungnoen
 
PDF
Learn backend java script
Tsuyoshi Maeda
 
PPTX
Intro To Node.js
Chris Cowan
 
PPT
Building your first Node app with Connect & Express
Christian Joudrey
 
PDF
Getting started with node JS
Hamdi Hmidi
 
PPTX
Building and Scaling Node.js Applications
Ohad Kravchick
 
KEY
nodecalgary1
Eric Kryski
 
PDF
Web Development with AngularJS, NodeJS and ExpressJS
João Rocha da Silva
 
ODP
Nodejs Intro - Part2 Introduction to Web Applications
Budh Ram Gurung
 
KEY
Writing robust Node.js applications
Tom Croucher
 
PPTX
Untangling spring week10
Derek Jacoby
 
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
Introduction to node.js
Adrien Guéret
 
NodeJS
Alok Guha
 
nodejs tutorial foor free download from academia
rani marri
 
Introduction to Node.js
Winston Hsieh
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
Building a real life application in node js
fakedarren
 
Download full ebook of Learning Node Shelley Powers instant download pdf
zeitsloyerqy
 
Introduction to Node.js
Somkiat Puisungnoen
 
Learn backend java script
Tsuyoshi Maeda
 
Intro To Node.js
Chris Cowan
 
Building your first Node app with Connect & Express
Christian Joudrey
 
Getting started with node JS
Hamdi Hmidi
 
Building and Scaling Node.js Applications
Ohad Kravchick
 
nodecalgary1
Eric Kryski
 
Web Development with AngularJS, NodeJS and ExpressJS
João Rocha da Silva
 
Nodejs Intro - Part2 Introduction to Web Applications
Budh Ram Gurung
 
Writing robust Node.js applications
Tom Croucher
 
Untangling spring week10
Derek Jacoby
 
Ad

More from Laurence Svekis ✔ (20)

PDF
Quiz JavaScript Objects Learn more about JavaScript
Laurence Svekis ✔
 
PDF
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
PDF
JavaScript Lessons 2023
Laurence Svekis ✔
 
PDF
Top 10 Linkedin Tips Guide 2023
Laurence Svekis ✔
 
PDF
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
PDF
Code examples javascript ebook
Laurence Svekis ✔
 
PDF
Javascript projects Course
Laurence Svekis ✔
 
PDF
10 java script projects full source code
Laurence Svekis ✔
 
PDF
Chrome DevTools Introduction 2020 Web Developers Guide
Laurence Svekis ✔
 
PDF
Brackets code editor guide
Laurence Svekis ✔
 
PDF
Web hosting get start online
Laurence Svekis ✔
 
PDF
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
PDF
Web hosting Free Hosting
Laurence Svekis ✔
 
PDF
Web development resources brackets
Laurence Svekis ✔
 
PPTX
Google Apps Script for Beginners- Amazing Things with Code
Laurence Svekis ✔
 
PPTX
JavaScript DOM - Dynamic interactive Code
Laurence Svekis ✔
 
PPTX
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
PPTX
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
PPTX
JavaScript Objects and OOP Programming with JavaScript
Laurence Svekis ✔
 
PPTX
JavaScript Core fundamentals - Learn JavaScript Here
Laurence Svekis ✔
 
Quiz JavaScript Objects Learn more about JavaScript
Laurence Svekis ✔
 
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
JavaScript Lessons 2023
Laurence Svekis ✔
 
Top 10 Linkedin Tips Guide 2023
Laurence Svekis ✔
 
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
Code examples javascript ebook
Laurence Svekis ✔
 
Javascript projects Course
Laurence Svekis ✔
 
10 java script projects full source code
Laurence Svekis ✔
 
Chrome DevTools Introduction 2020 Web Developers Guide
Laurence Svekis ✔
 
Brackets code editor guide
Laurence Svekis ✔
 
Web hosting get start online
Laurence Svekis ✔
 
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
Web hosting Free Hosting
Laurence Svekis ✔
 
Web development resources brackets
Laurence Svekis ✔
 
Google Apps Script for Beginners- Amazing Things with Code
Laurence Svekis ✔
 
JavaScript DOM - Dynamic interactive Code
Laurence Svekis ✔
 
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
JavaScript Objects and OOP Programming with JavaScript
Laurence Svekis ✔
 
JavaScript Core fundamentals - Learn JavaScript Here
Laurence Svekis ✔
 
Ad

Recently uploaded (20)

PPTX
What Is Data Integration and Transformation?
subhashenia
 
PDF
apidays Singapore 2025 - Trustworthy Generative AI: The Role of Observability...
apidays
 
PPTX
04_Tamás Marton_Intuitech .pptx_AI_Barometer_2025
FinTech Belgium
 
PDF
SQL for Accountants and Finance Managers
ysmaelreyes
 
PPTX
apidays Singapore 2025 - The Quest for the Greenest LLM , Jean Philippe Ehre...
apidays
 
PPTX
05_Jelle Baats_Tekst.pptx_AI_Barometer_Release_Event
FinTech Belgium
 
PDF
Business implication of Artificial Intelligence.pdf
VishalChugh12
 
PDF
apidays Singapore 2025 - Streaming Lakehouse with Kafka, Flink and Iceberg by...
apidays
 
PPTX
BinarySearchTree in datastructures in detail
kichokuttu
 
PDF
Optimizing Large Language Models with vLLM and Related Tools.pdf
Tamanna36
 
PPTX
在线购买英国本科毕业证苏格兰皇家音乐学院水印成绩单RSAMD学费发票
Taqyea
 
PPT
tuberculosiship-2106031cyyfuftufufufivifviviv
AkshaiRam
 
PDF
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 
PDF
Driving Employee Engagement in a Hybrid World.pdf
Mia scott
 
PDF
Group 5_RMB Final Project on circular economy
pgban24anmola
 
PPTX
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
PPTX
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
PPTX
Feb 2021 Ransomware Recovery presentation.pptx
enginsayin1
 
PPT
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
PDF
Unlocking Insights: Introducing i-Metrics Asia-Pacific Corporation and Strate...
Janette Toral
 
What Is Data Integration and Transformation?
subhashenia
 
apidays Singapore 2025 - Trustworthy Generative AI: The Role of Observability...
apidays
 
04_Tamás Marton_Intuitech .pptx_AI_Barometer_2025
FinTech Belgium
 
SQL for Accountants and Finance Managers
ysmaelreyes
 
apidays Singapore 2025 - The Quest for the Greenest LLM , Jean Philippe Ehre...
apidays
 
05_Jelle Baats_Tekst.pptx_AI_Barometer_Release_Event
FinTech Belgium
 
Business implication of Artificial Intelligence.pdf
VishalChugh12
 
apidays Singapore 2025 - Streaming Lakehouse with Kafka, Flink and Iceberg by...
apidays
 
BinarySearchTree in datastructures in detail
kichokuttu
 
Optimizing Large Language Models with vLLM and Related Tools.pdf
Tamanna36
 
在线购买英国本科毕业证苏格兰皇家音乐学院水印成绩单RSAMD学费发票
Taqyea
 
tuberculosiship-2106031cyyfuftufufufivifviviv
AkshaiRam
 
InformaticsPractices-MS - Google Docs.pdf
seshuashwin0829
 
Driving Employee Engagement in a Hybrid World.pdf
Mia scott
 
Group 5_RMB Final Project on circular economy
pgban24anmola
 
Aict presentation on dpplppp sjdhfh.pptx
vabaso5932
 
ER_Model_with_Diagrams_Presentation.pptx
dharaadhvaryu1992
 
Feb 2021 Ransomware Recovery presentation.pptx
enginsayin1
 
Growth of Public Expendituuure_55423.ppt
NavyaDeora
 
Unlocking Insights: Introducing i-Metrics Asia-Pacific Corporation and Strate...
Janette Toral
 

Local SQLite Database with Node for beginners

  • 1. Node and SQLLite SQLite Database with Node https://www.udemy.com/node- database/?couponCode=SLIDESHARE
  • 2. INSTRUCTOR: LAURENCE SVEKIS Course instructor : Laurence Svekis - Over 300 courses in technology and web applications. - 20 years of JavaScript web programming experience - 500,000+ students across multiple platforms - Digital instructor since 2002 READY TO HELP YOU LEARN and ANSWER ANY questions you may have.
  • 3. Windows Terminal Windows - https://cmder.net/ or use the command prompt terminal Launch the Command Prompt - use the Run window or press the Win + R keys on your keyboard. Then, type cmd and press Enter. List current directory of files - dir Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 4. Mac Terminal Open Terminal by pressing Command+Space or select terminal in the applications list. List current directory of files - ls Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 5. Command Line Launch One node is installed check to see version installed. Type node -v Open your editor and create a js file that contains console.log('Hello World'); save it as test.js In the terminal type node test.js and watch for a result. What gets returned? NPM - check if its installed npm -v latest version install npm install npm@latest -g
  • 6. Create app js file Create a main app js file to run your node application. touch app.js
  • 7. Install setup Node and Express https://nodejs.org/en/download/ Select the platform and install Setup of Localhost machine https://expressjs.com/ In the terminal node -v npm install express --save
  • 8. Npm package.json Install all the dependencies for your project. Create a package.json file. You can also install packages using Optional flags --save - installs and adds to the package.json --save-dev - installs and adds to the package.json under devDependencies. Updating packages - check all packages or specific package. npm install <package-name> npm update npm update <package-name>
  • 9. Npm install Packages Default its installed under the current tree. Npm init to create package.json Also adds the dependencies to the package.json file in current folder. Global installations of the package can be done by adding the flag -g. Will install package to global location. Get global root folder. npm init npm install -g <package-name> npm root -g
  • 10. Npm uninstall Packages Default its installed under the current tree. Also adds the dependencies to the package.json file in current folder. Global installations of the package can be done by adding the flag -g. Will install package to global location. Get global root folder. npm uninstall <package-name> npm install -g <package-name> npm root -g
  • 11. Setup - Local Server Run app.js and Open Browser to localhost:8080 - port with http path. Assign variable to app object. Open http://localhost:8080/ in your browser. const express = require('express') const app = express() app.get('/', function (req, res) { res.send('ready') }) app.listen(8080, function () { console.log('Server ready') }) const express = require('express') const app = express() app.get('/', function (req, res) { res.send('ready') }) const server = app.listen(8080, function () { console.log('Server ready') }) node app.js
  • 12. NodeMon Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. npm install -g nodemon https://nodemon.io/ Run it nodemon app.js ** make some changes no more node restart typing ;)
  • 13. Setup - Local Express Server Run app.js and Open Browser to localhost:8080 - port with http path. Assign variable to app object. Open http://localhost:8080/ in your browser. const express = require('express'); const app = express(); const port = 8080; const server = app.listen(port, function () { console.log('Server ready') }) app.get('/', function (req, res) { res.json({ "status": "ready" }) }) app.use(function (req, res) { res.status(404); }); nodemon app.js
  • 14. Install SQLlite and MD5 for hash of passwords https://www.npmjs.com/package/sqlite3 SQLite is a relational database management system contained in a C library. In contrast to many other database management systems, SQLite is not a client–server database engine. Rather, it is embedded into the end program. https://www.sqlite.org/about.html npm install sqlite3 a JavaScript function for hashing messages with MD5. https://www.npmjs.com/package/md5 npm install md5
  • 15. Setup - Database and create Table Create a new js file to setup a database. const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); db.run('CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT,first,last,email,password)'); db.close(); touch dbsetup.js mkdir db node dbsetup.js touch insert.js touch insert.js Create a new js file to insert to the database. Add to database new users table. Catch the errors const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis", "[email protected]", "password")'; db.run(sql, [], function(err) { if (err) { return console.log(err.message); } console.log(`Rowid ${this.lastID}`); }); db.close();
  • 16. Database as module Setup the db.js file as the database connection, useful if you need to change file locations. Use a module const sqlite3 = require('sqlite3').verbose(); const db = new sqlite3.Database('./db/user.db'); module.exports = db; **** On app.js add const db = require("./db.js") touch db.js
  • 17. Query Database for users Querying all rows with all() method - Will output all the contents of the database. const sqlite3 = require('sqlite3').verbose(); const md5 = require('md5'); const db = new sqlite3.Database('./db/user.db'); module.exports = db; **** On app.js add const db = require("./db.js") const db = require("./db.js") const query = "select * from users"; db.all(query, function (err, rows) { if (err) { throw err; } rows.forEach(function (row) { console.log(row); }); });
  • 18. List users in web page Using express setup a new route for users const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) app.get('/users', function (req, res) { const query = "select * from users"; db.all(query, function (err, rows) { if (err) { throw err; } res.json({ "data": rows }); }); }) app.get('/', function (req, res) { res.json({ "status": "ready" }) }) app.use(function (req, res) { res.status(404); });
  • 19. List get users by id In the browser go to the users folder and add an id value at the end. app.get("/users/:id", function (req, res) { const query = "select * from users where id = ?" const params = [req.params.id] db.get(query, params, function (err, row) { if (err) { throw err; } res.json({ "data": row }) }); });
  • 20. Create new User Create the browser side add.html file with a form for inputs and event listener to send request. For node setup install of body-parser https://github.com/expressjs/body-parser body parsing middleware <form> <input type='text' name='first' value='Laurence'> <input type='text' name='last' value='Svekis'> <input type='text' name='email' value='[email protected]'> <input type='text' name='password' value='secret'> <input type='submit'> </form> <script> const myForm = document.querySelector('form'); const inputs = document.querySelectorAll('input'); myForm.addEventListener("submit", function (evt) { evt.preventDefault(); fetch('/adder', { method: 'POST' , body: JSON.stringify({ first: inputs[0].value , last: inputs[1].value , email: inputs[2].value , password: inputs[3].value , }) , headers: { "Content-Type": "application/json" } }).then(function (response) { return response.json() }).then(function (body) { console.log(body); }); }); </script> npm install body-parser
  • 21. Node get new user data Submit the form and check for request data from the body in the console. const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true })); app.post('/adder', function (req, res) { console.log(req.body); console.log('req.body.first', req.body['first']); })
  • 22. Add new user to database Update post to insert into database. You can go to users to list all http://localhost:8080/users const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true })); app.post('/adder', function (req, res) { console.log(req.body); let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)' db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']], function (err, row) { if (err) { throw err; } res.json({ "data": this.lastID }) }); }) app.use(function (req, res) { res.status(404); });
  • 23. Full Source Code app.js app.get('/', function (req, res) { res.json({"status": "ready"}) }) app.get('/new', function (req, res) { res.sendFile(__dirname + '/add.html'); }) app.post('/adder', function (req, res) { console.log(req.body); let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)' db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']], function (err, row) { if (err) {throw err;} res.json({"data": this.lastID }) }); }) app.use(function (req, res) { res.status(404); }); const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () {console.log('Server ready')}) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/users', function (req, res) { const query = "select * from users"; const params = []; db.all(query, params, function (err, rows) { if (err) {throw err;} res.json({"data": rows}); }); }) app.get("/users/:id", function (req, res) { const query = "select * from users where id = ?" const params = [req.params.id] db.get(query, params, function (err, row) { if (err) {throw err;} res.json({ "data": row }) }); });
  • 24. Full Source Code other files <!-- add.html --> <form><input type='text' name='first' value='Laurence'><input type='text' name='last' value='Svekis'><input type='text' name='email' value='[email protected]'><input type='text' name='password' value='secret'><input type='submit'> </form> <script> const myForm = document.querySelector('form'); const inputs = document.querySelectorAll('input'); myForm.addEventListener("submit", function (evt) { evt.preventDefault(); fetch('/adder', { method: 'POST' , body: JSON.stringify({first: inputs[0].value, last: inputs[1].value, email: inputs[2].value, password: inputs[3].value }) , headers: {"Content-Type": "application/json" } }).then(function (response) { return response.json() }).then(function (body) { console.log(body); }); }); </script> //db.js const sqlite3 = require('sqlite3').verbose() const md5 = require('md5') const db = new sqlite3.Database('./db/user.db'); module.exports = db //dbsetup.js const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); db.run('CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT,first,last,email,password)'); db.close(); const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis", "[email protected]", "password")'; db.run(sql, [], function(err) { if (err) { return console.log(err.message); } console.log(`Rowid ${this.lastID}`); }); db.close();
  • 25. Congratulations on completing the section Course instructor : Laurence Svekis - providing online training to over 500,000 students across hundreds of courses and many platforms. Find out more about my courses at http://www.discoveryvip.com/