0% found this document useful (0 votes)
60 views

Node JS&SQLite Connection&CODECADEMY

Node.js comes with a Read-Eval-Print Loop (REPL) that allows immediate feedback for code testing and evaluation. The global object contains Node-specific globals and properties that can be accessed or assigned. The process object provides information about the current process like environment variables and command line arguments. Node uses a modular system where files are modules that can be required and imported into other files. Asynchronous functions use callbacks and error-first patterns to handle responses without blocking.

Uploaded by

Java Project
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Node JS&SQLite Connection&CODECADEMY

Node.js comes with a Read-Eval-Print Loop (REPL) that allows immediate feedback for code testing and evaluation. The global object contains Node-specific globals and properties that can be accessed or assigned. The process object provides information about the current process like environment variables and command line arguments. Node uses a modular system where files are modules that can be required and imported into other files. Asynchronous functions use callbacks and error-first patterns to handle responses without blocking.

Uploaded by

Java Project
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Cheatsheets / Learn Node.

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")

// REPL has evaluated the line and has printed out HI


HI

Node.js Global Object


The Node.js environment has a global object that contains every Node-speci c global
property. The global object can be accessed by either typing in //Two ways to access global
console.log(global) or global in the terminal after RPL is running. In order > console.log(global)
to see just the keys Object.keys(global) can be used. Since global is an object, //or
new properties can be assigned to it via global.name_of_property = > global
'value_of_property' .
//Adding new property to global
> global.car = 'delorean'

Node.js Process Object


A process is the instance of a computer program that is being executed. Node has a global
process object with useful properties. One of these properties is NODE_ENV which can be if (process.env.NODE_ENV === 'development'){
used in an if/else statement to perform di erent tasks depending on if the application is in console.log('Do not deploy!! Do not deploy!!');
the production or development phase. }
Node.js process.argv
process.argv is a property that holds an array of command-line values provided
when the current process was initiated. The rst element in the array is the absolute path to node web.js testing several features
the Node, followed by the path to the le that’s running and nally any command-line console.log(process.argv[2])// 'features' will be printed
arguments provided when the process was initiated.

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.

Node.js Core Modules


Node has several modules included within the environment to e ciently perform common
tasks. These are known as the core modules. The core modules are de ned within Node.js’s let http = require('http');
source and are located in the lib/ folder. A core module can be accessed by passing a
string with the name of the module into the require() function.
Node.js Local Modules
In Node.js les are considered modules. Modules that are created locally are called local
modules. These local modules are held in an object called module . This object has a // type.js
property called export which allows a module to be accessed in a di erent module. // by using the export property we can use this module in
another file
module.exports = class key {
constructor(car) {
this.car = car;
}
};

// qwerty.js
// by requiring the type.js file we can we use the module in
the type.js file
let Dog = require('./type.js');

Node Package Manager


NPM stands for node-package-manager. An NPM is essentially a collection of code from
other developers that we can use. When Node is installed the npm command-line tool is
downloaded as well. This command-line tool enables us to interact with the registry via our
terminal.
EventEmitter Class
Node.js has an EventEmitter class which can be accessed by requiring the events core
module. Each event emitter instance has an .on() method which assigns a listener // Require in the 'events' core module
callback function to a named event. EventEmitter also has an .emit() method which let events = require('events');
announces a named event that has occurred.
// Create an instance of the EventEmitter class
let myEmitter = new events.EventEmitter();
let version = (data) => {
console.log(`participant: ${data}.`);
};

// Assign the version function as the listener callback for


'new user' events
myEmitter.on('new user', version)

// Emit a 'new user' event


myEmitter.emit('new user', 'Lily Pad')
// 'Lily Pad'

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.

// endgame will run after 1000ms


setTimeout(endgame, 1000);
Asynchronous Error Handling
The Node environment has all the standard JavaScript errors as well as the JavaScript Error
class for creating new error instances. Many asynchronous Node APIs use error- rst callback
functions: callback functions which have an error as the rst expected argument and the
data as the second argument. If the asynchronous task results in an error, it will be passed in
as the rst argument to the callback function. If no error was thrown, the rst argument will
be undefined .

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
};

// assigning return value


const server = http.createServer(requestListener);

// assigning server port


server.listen(3000);

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)");

//updating existing table


db.run('INSERT INTO Key (type, color) VALUES ($type, $color)

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);
}

You might also like