Nodejs website
nodejs
?Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
Event-driven ✦ Non-blocking I/O
var fs = require('fs');
fs.readFile('subejects.txt', 'utf8', function(err, contents) {
console.log(contents);
});
console.log('after calling readFile');
JS Practice + Refresher
Step 1
Using the above image - define an array that holds each of the items above.
Step 2
Create a function that array and output each of the items in the array you created
Step 3
Create a function that accepts an array as an argument and returns the text "YES" if lentils is within the array.
Core/Built-in Modules ✦ Third-Party Modules
const welcome = require('./welcome'); //including a module that is a file within your program
const http = require('http'); //including a core module example
const app = require('express'); //including third-party module example
exports.welcome = function(){
console.log("You called the welcome method");
}
exports.conclude = ()=>{
console.log("You called the conclude method");
}
/**The require() function takes one argument of a relative file
path of where the file is located **/
const outputInfo = require('./welcome.js');
outputInfo.welcome(); /** Outputs info to console **/
outputInfo.conclude(); /** Outputs info to console **/
NPM
?NPM is the package manager for JavaScript and the world’s largest software registry. Discover packages of reusable code — and assemble them in powerful new ways.
npmjs.com
Download standalone tools you can use right away.
Share code with any npm user, any where
Form virtual teams (orgs)
Manage multiple versions of code and code dependencies.
Update applications easily when underlying code is updated.
Discover multiple ways to solve the same puzzle.
//installing nodemon
npm install --save-dev nodemon
//installing uniq :: https://www.npmjs.com/package/eslint
npm install eslint --save-dev
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route.
Express Getting started Guide
const express = require('express')
const app = express()
const port = 3000
/**To serve static files such as images, CSS files, and JavaScript files, create a folders
* and include the below statement. The below statement assumes that I have a folder named assets
**/
app.use(express.static('assets'))
// view engine setup -> We'll use handlebars.js as our templating engine
app.set('view engine', 'html');
// allows our application to use .html extension | *Create a views folder and add your HTML documents
app.engine('html', require('hbs').__express);
// parse application/json
app.use(express.json());
// For parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// Routes
app.get('/', function (req, res) {
console.log("Sent as a get request");
res.render('home', { title: "Routing in Action!"})
})
app.get('/users/:id', function (req, res) {
//Getting id parameter
var id = req.params.id;
console.log("Sent as a get request");
res.render('home', { title: "Routing in Action!", user_id : id})
})
app.get('/contact', function (req, res) {
res.render( 'contact', {title : "Contact Page"})
})
app.post('/submit', function (req, res) {
//Getting body parameters
var data = req.body;
var firstName = data.fname;
var lastName = data.lname;
var id = data.id;
console.log("Sent as a post request");
console.log(firstName + " " + lastName + " " + id );
res.render( 'contact', {title : "Contact Page"})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Individual Practice
Using the code from the example we just went through, create a new route that listens for a GET request from the URL below
localhost:3000/movie/101
Step 1
Copy the code from instructors example and start up the server to make sure application properly functions
Step 2
Once the route is created, create a view that displays the id number back to the client
SQLite - Configuration steps below:
When incorporating a database, we need both the drivers and functionality to configure our session store
npm install sqlite3 //install sqlite database drivers
npm install connect-sqlite3 //install module to configure session store *Needed for authentication
Create a config file that will store your configurtion
var sqlite3 = require('sqlite3').verbose() //npm install sqlite3
//Creating a new database instance - Indication of connected database
//Before peforming any operations to database, make sure database is connected.
let db = new sqlite3.Database('./artist_album.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
}else{
//Successful database connection
console.log('Connected to the SQLite database.')
}
});
Helpful to place database operations into a file and import database functions into other parts of program when needed.
Helpful resource on querying database https://www.sqlitetutorial.net/
var sqlite3 = require('sqlite3').verbose() //npm install sqlite3
//Creating a new database instance - Indication of connected database
//Before peforming any operations to database, make sure database is connected.
let db = new sqlite3.Database('./artist_album.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
}else{
//Successful database connection
console.log('Connected to the SQLite database.')
}
});
//Get Artist and Album
let getAllArtistAndAlbums = (res) =>{
//var getArtistAndAlbumSQL = 'SELECT ?,?,?,?,? FROM Album INNER JOIN artist ON Album.album_artistID = Artist.artistID';
var getArtistAndAlbumSQL = 'SELECT artistID,artist_name,album_name,album_release_year,album_genre FROM Album INNER JOIN artist ON Album.album_artistID = Artist.artistID';
var params =["artistID","artist_name", "album_name", "album_release_year", "album_genre"];
db.all(getArtistAndAlbumSQL, (err, rows) => {
if (err) {
throw err;
}
res.render('index', {rows})
/**rows.forEach((row) => {
console.log(row.album_name);
});*/
});
}
//Create a Artist
let createArtist = (artistalbum) =>{
var createArtistSql ='INSERT INTO Artist (artist_name) VALUES (?)' //Paramaterized Query
var params =[artistalbum.artistName];
db.run(createArtistSql, params, function(err){
if (err){
return console.log(err.message);
}
console.log("Artist Created");
console.log(`Rows inserted ${this.changes}`);
});
getArtist(artistalbum);
}
//Return a Artist
let getArtist = (artistalbum) =>{
var getArtistSql ="SELECT artistID, artist_name FROM Artist WHERE artist_name = ?"; //Paramaterized Query
var params =[artistalbum.artistName];
console.log(artistalbum.artistName);
//var params=['Michael Jackson'];
db.get(getArtistSql, params, async function(err, row){
if (err){
return console.log(err.message);
}
console.log(row);
//Create Album once we receive the returned ID
await createAlbum(artistalbum, row.artistID);
});
}
//Create a Album
let createAlbum = (album, artistID) =>{
var createAlbumSql ='INSERT INTO Album(album_name,album_release_year,album_genre,album_artistID) VALUES (?,?,?,?)' //Paramaterized Query
var params =[ album.albumTitle,album.albumRelease,album.albumGenre,artistID];
db.run(createAlbumSql, params, function(err){
if (err){
return console.log(err.message);
}
console.log("Album Created");
console.log(`Rows inserted ${this.changes}`);
});
}
//Update record
let deleteRecord = (id) =>{
console.log("Delete Record Function triggered");
//var deleteArtistAndAlbumSql ='DELETE FROM Album WHERE album_artistID= ?' //Paramaterized Query
var deleteArtistAndAlbumSql = 'DELETE Artist FROM Artist INNER JOIN artist ON Album.album_artistID = Artist.artistID WHERE Album.album_artistID = ?';
var params =[id];
db.run(deleteArtistAndAlbumSql, params, function(err){
if (err){
return console.log(err.message);
}
console.log("Album and Artist Deleted");
console.log(`Rows deleted ${this.changes}`);
});
}
//Export functions to be used in other areas of program.
module.exports = {getAllArtistAndAlbums, createArtist, getArtist, deleteRecord, createAlbum}
Step 1
Open DB Browser and create a new database. Name the database "activitydb" and create a table that reflects the columns in the above image.
Step 2
Execute commands to 1) INSERT data and 2) Return all the data found in table and 3) Provide the average age of all entries in table.
Step 3
Document your queries in a file called learning_activity.sql and post to the the discussion board topic. Include the learning_activity.sql file and the activitydb.db
Step 1
Open DB Browser and create a new database. Name the database "activitydb" and create a table that reflects the columns in the above image.
Step 2
Execute commands to 1) INSERT data and 2) Return all the data found in table and 3) Provide the average age of all entries in table.
Step 3
Document your queries in a file called learning_activity.sql and post to the the discussion board topic. Include the learning_activity.sql file and the activitydb.db