Node JS&SQLite Connection&CODECADEMY
Node JS&SQLite Connection&CODECADEMY
js
Introduction to Node.js
Node.js REPL
Node.js comes with REPL, an abbreviation for read–eval–print loop. REPL contains three
di erent states: //node is typed in the console to access REPL
*a read state where it reads the input from a user, *the eval state where it evaluates the $ node
user’s input *the print state where it prints out the evaluation to the console.
After these states are nished REPL loops through these states repeatedly. REPL is useful as
//the > indicates that REPL is running
it gives back immediate feedback which can be used to perform calculations and develop
// anything written after > will be evaluated
code.
> console.log("HI")
Node.js process.memoryUsage()
process.memoryUsage() is a method that can be used to return information on
the CPU demands of the current process. Heap can refer to a speci c data structure or to //using process.memoryUsage() will return an object in a
the computer memory. format like this:
{ rss: 26247168,
heapTotal: 5767168,
heapUsed: 3573032,
external: 8772 }
Node.js Modules
In Node.js les are called modules. Modularity is a technique where one program has distinct
parts each providing a single piece of the overall functionality - like pieces of a puzzle let baseball = require(./babeRuth.js)
coming together to complete a picture. require() is a function used to bring one
module into another.
// qwerty.js
// by requiring the type.js file we can we use the module in
the type.js file
let Dog = require('./type.js');
Asynchronous Node.js
Node.js is a non-blocking, asynchronous environment. The event loop in Node.js enables
asynchronous actions to be handled in a non-blocking way. Node.js provides APIs which let endgame = () => {
allow operations to be put in a queue, waiting to be executed after the previous operation console.log('I am inevitable')
nishes. If synchronous tasks never end, operations waiting in the event-queue will never };
execute.
Node.js Input/Output
Input is data that is given to the computer, while output is any data or feedback that a
computer provides. In Node, we can get input from a user by using the stdin.on() // Recieves an input
method on the process object. We are able to use this because .on() is an process.stdin.on();
instance of EventEmitter. To give an output we can use the .stdout.write()
// Gives an output
method on the process object as well. This is because console.log() is a thin
process.stdout.write();
wrapper on .stdout.write() .
Filesystem
A lesystem is how you access and organize all data on a computer. The Node.js fs core
module is an API for interacting with the le system. Each method available through the fs
// First argument is the file path
module has a synchronous version and an asynchronous version. One of the methods in the // The second argument is the file’s character encoding
fs core module is the .readfile() method which allows us to read data from a // The third argument is the invoked function
le. fs.readFile('./file.txt', 'utf-8', CallbackFunction);
Web Server
Node was designed with back end development needs as a top priority. One of these needs
is the ability to create web servers. A web server is a computer process that listens for const http = require('http');
requests from clients and returns responses. A Node core module designed to meet these
needs is the http module. This module has functions that simplify receiving and responding
to requests.
Creating A Server
http.createServer() is a method that returns an instance of an
http.server . The method .listen() in http.server tells the server to // required in the http core module.
const http = require('http');
“listen” for incoming connections. We give http.createServer() a callback
function also known as the requestListener , which will be triggered once the
let requestListener = (request, response) => {
server is listening and receives a request. The requestlistener requests a request object and
a response object.
// code to be filled in depending on server
};
Readable/Writable Streams
In most cases, data isn’t processed all at once but rather piece by piece. This is what we call
streams. Streaming data is preferred as it doesn’t require tons of RAM and doesn’t need to // Readable stream
have all the data on hand to begin processing it. To read les line-by-line, we can use the readline.createInterface();
.createInterface() method from the readline core module. We can write to
streams by using the .createWriteStream() method. // Writtable Stream
fs.createWriteStream();
Cheatsheets / Learn Node-SQLite
Learn Node-SQLite
sqlite3 Module
Node.js and SQLite are separate entities, but both can be used together to create powerful
applications. First, we need to link them together by requiring the sqlite3 module. Once we //requiring the sqlite3 module
have required this module in our JavaScript, it will give us access to methods to perform
various actions with the database. const sqlite3 = require('sqlite3');
Creating/Connecting To A Database
In SQLite, a database corresponds to a single le. The sqlite3.Database()
method can be used to create or connect to a single le. // creating a database file
const db = new sqlite3.Database('./db.sqlite');
db.get() Method
Sometimes we only need one row from a database. The method db.get() allows us to
fetch a single row from a database matching a query. If multiple rows match the query only // This will return the first row matching the query.
one row matching the query will be returned. db.get("SELECT * FROM drinks WHERE type = 'soda'")
db.all() Method
A query is a statement that speaks to a database and requests speci c information from it.
The db.all() method allows us to execute a query that returns all rows with speci c // Selects a table named Animal and returns only the rows
data. For example, we can use db.all() to return all rows from a table that has the pet the has the pet as a cat
as a cat. db.all("SELECT * FROM Animal WHERE pet = 'cat'")
db.each() Method
Sometimes we want to perform an action every time a row is returned. Using the
db.each() method we can do exactly that. db.each() takes a query and a db.each("SELECT * FROM Sports WHERE type = 'baseball'",
callback function that it performs on each row returned from the query. db.each() (error, row) => {
can also take a second callback function, which will be called when all of the queries are // This will be printed everytime a row is returned
completed and processed. console.log(`${row.name} is a good baseball team`);
};
db.run() Method
Sometimes we want to do more than just get a result from a database. The db.run()
method holds SQL commands that do not return rows; such as commands that will allow us //creating a table
to create, update tables, or insert new rows. db.run("CREATE TABLE user (id INT, dt TEXT)");
db.serialize() Method
Any requests we send to our database get processed as quickly as possible, which can lead to
multiple requests processing at the same time. Usually, this creates e ciency but in some //each request inside this method will be executed one by
cases like when we want to create a table and insert rows, it can cause errors. This is because one
our request might try to insert a row into a table that’s not even created yet. This problem db.serialize(() => {
can be solved by the db.serialize() method which takes multiple requests and db.run("DROP TABLE Stocks");
executes them one by one. db.run("CREATE TABLE Stocks");
db.run("INSERT INTO Stocks (AMD, MSFT, TSLA);
});
Handling Errors
sqlite3 uses Node.js error- rst callback style.The rst argument in the methods
db.run() , db.each() , db.get() , and db.all() will always be an Error // an if statement can be used to log the error
object. This object will return an error if it exists and return null if no errors are found. if (err) {
console.log(err);
}