Provide an exemplary request to application flow
How is JavaScipt running on a browser?
What is node.js?
runtime environment for JS code
-> previous: did only run in browser…
What is the nature of node.js ?
single threaded
event driven
non-blocking
asynchronous
What is the event-loop in node.js responsible for?
allows node.js to perform
non-blocking I/O operatoins
despite fact that java scrip tis single-threaded
=> by assigning operations to the OS
How does the event-loop in node.js roughly work?
has event queue that is processed FIFO
registers callbacks for intensive operations (i.e. file system, db access, computation) to OS
non-intensive / non-outsourced events and callbacks (response from registered, finished callbacks) are in event queue
When should one use Node.js?
real-time applications
process high volume of short messages
requiring low latency
fast and scalable environemnt
ability to process many requests with low response time
greate fit for modern web applications carrying out lots of processing on the client side
When should one not make use of Node.js?
CPU-heavy jobs
single-thread -> uses only one CPU core
CPU-heavy operations will just block incoming requests, rendering biggest advantage of Node.js useless
simple web applications
superfluous
we dont need separate API and all data comes from server…
What is the node package manager (npm)?
used to install node programs/modules
like pip but for node.js
modules get installed inside “node_modules” folder
What commands did we discuss for npm?
npm install express
//install express module
-> folder in local projcet where all dependencies are installed
npm install express —save
// install express module and add in package.json
npm install -g express
// install express globally
What are popular modules?
express
web development framework
connect
extensible http server framework
socket.io
server side component for websocket
mongo/mongoose
wrappers to interact with mongo database
What is the file package.json for?
presnt inside root folder of your package / application
tells npm how package is structured and what all dependencies need to be installed
What are elements of the package.json file?
What is a REST API?
communication paradigm for client server architectures
Representational state transfer
resource based - deals with things instead of actions (like a person, address,…)
transfer typically using json or xml
What constraints characterize a rest api?
uniform interface
stateless
client-server
cacheable
layered system
code on demand (optional)
How are uniform interfaces expressed in REST apis?
use HTTP actions
get
post
put
delete
uniform resource identifiers (URI)
-> resource names
HTTP response
status, body
What means stateless w.r.t. rest api?
server contains no client state
no session
no history
each request contains enough context to process message
What means client-server w.r.t. rest api?
Client application and server application MUST be able to evolve separately without any dependency on each other
What means cacheable w.r.t. rest api?
caching can be applied to resources when applicable
and these resources MUST be declared cacheable.
Caching can be implemented on the server or client side.
What means layered system w.r.t. rest api?
Uses layered system architecture where for example
we deploy the APIs on server A,
and store data on server B
and authenticate requests in Server C.
What means code on demand w.r.t. rest api?
Most of the time we will be sending the static representations of resources in form of XML or JSON.
Can return executable code to support a part of your application
e.g. clients may call API to get a UI widget rendering code.
Explain an exemplary REST API request and response (json)
What are the main characteristics of MongoDB?
open source document database
high performance
high availability
automatic scaling
NoSQL database
uses JSON like documents to store information
How does a record in MongoDB look like?
document
-> datastructure with field and value pairs
What is a collection and database in MongoDB?
collection:
grouping of MongoDB documents
databases
collections of documents
How to define a MongoDB schema in Node.js?
we are making use of Mongoose
Import Mongoose
const mongoose = require(‘mongoose’),
Schema = mongoose.Schema;
Creating Schema for Object (in our case Book)
const BooksSchema = new Schema({
title: String,
…
});
creating mongoose model (wrapper for schema)
const BooksModel =
mongoose.model(‘books’, BooksSchema);
export model to be usable in other program with import…
module.exports = BooksModel;
How can we consolidate schemas (i.e. Books.js, Authors.js, …)?
have extra file like Index.js consolidating all DB schemas
connect to MongoDB (running locally at localhost:27017
const mongoose = require(“mongoose”);
mongoose.connect(process.env.MONGODB_URI
|| “mongodb://localhost:27017/booksData”,
{useNewUrlParser: true});
export it
module.export.books =
require(“./books.js”);
How can we create a webserver with node.js?
server.js -> start web server an contains all API endpoints
create web server using express
const express = require(‘express’);
const app = express();
How do we declare an Root endpoint?
when accessing i.e. root endpoint (http://example.com/)
calls the function homepage
which (as defined here)
sends the index.html file in the response (res)
app.get(‘/’, function homepage(req, res){
res.sendFile(__dirname +
‘/views/index.html’);
How do we declare an API endpoint?
when accessing http://example.com/api
sends some json information…
=> is syntactic sugar to define a function…
app.get(‘/api’, (req, res) => {
res.json([…])
How can we set the static file directory in node.js?
app.use(express.static(__dirname +
‘/public’));
this particular directory is called public…
What is an exemplary endpoint to get some book information?
app.get(‘/api/books/’, (req, res) => {
db.books.find({}, function (err,books) {
if (err) throw err;
res json(books);
uses books model and query to mongo database to get all ({}) objects stored
books is array of json objects -> returned to user…
How can we make node.js listen to specific port?
app.listen(process.env.PORT || 80, () => {
console.log(‘Express server is up and
running on http://localhost:80/’);
=> process.env.PORT | | 80
-> if environemnt variable is present
-> else use 80 as default…
How can we start a mongo database (terminal)?
mkdir data
here, all mongo db info is stored in some directory…
mongod —dbpaht=./data
Last changed2 years ago