Let’s talk about Node.js
Hello! Nils Mehlhorn freelance software engineer nils-mehlhorn.de @n_mehlhorn www @n_mehlhorn 2
What’s Views & Real Node.js? APIs World 3
What’s Let’s look at the Node.js basics 4
Node.js is ... … a JavaScript runtime … based on Chrome’s V8 engine … designed for scalable network apps … asynchronous event-driven ? … using non-blocking IO ?? 5
IO = Access to slow stuff ● network ● file system ● database 6
Blocking IO const fs = require('fs') const options = {encoding: 'utf-8'} // block const content = fs.readFileSync('./file.txt', options) console.log(content) console.log('(other things your app does)') Synchronous Call (JavaScript is single-threaded) 7
Non-Blocking IO const fs = require('fs') const options = {encoding: 'utf-8'} // no block, but async fs.readFile('./file.txt', options, (err, content) => { console.log(content) }) console.log('(other things your app does)') Asynchronous Callback 8
Node.js Event Loop Thread Thread readFile(cb) register Thread Event Loop Thread done cb() Worker JS Pool more: What the heck is the event loop anyway? 9
const fs = require('fs') Promises const options = {encoding: 'utf-8'} function getJsonFile(path, callback) { fs.readFile(path, options, (err, content) => { no “callback hell” ▣ if (err) { callback(err) less error-prone ▣ } const json = JSON.parse(content) chainable ▣ callback(null, json) }) } function getJsonFile(path) { return fs.promises.readFile(path, options) .then(content => JSON.parse(content)) } 10
Views & Let’s build for APIs the web 11
Express HTTP web service Request Handling Client View Rendering SQL browser Authentication Client Routing database fs Logging Express app Node.js file system 12
const express = require('express') const app = express() http://localhost:3000 app.get('/', (req, res) => { res.send('Hello World') }) const port = 3000 app.listen(port, () => { console.log('Server started') }) Hello World with Express 13
greet.ejs <!DOCTYPE html> <html> Views <head> <title><%= title %></title> </head> <body> <h1><%= title %></h1> <p>Hey there, <%= person %>!</p> app.set('views', './views')) </body> app.set('view engine', 'ejs') </html> app.get('/greet', (req, res) => { const data = { /greet?person=Delilah title: 'iJS', person: req.query.person } res.render('greet', data) }) 14
Includes Output <title><%= title %></title> <html> <body> <% include(../header, {title}) %> Control Flow <ul> <main>Hello</main> <% users.forEach(user => { %> <li><%= user.name %></li> <% include ../footer %> <% }) %> </ul> </body> </html> Embedded JavaScript Templates 15
APIs /todos [ let todos = [ { "id" : 1, {id: 1, text: "Do laundry", done: true}, "text" : "Do laundry" , {id: 2, text: "Prepare talk", done: true}, "done" : true }, {id: 3, text: "Go on vacation", done: false} { ] "id" : 2, "text" : "Prepare talk" , "done" : true app.get('/todos', (req, res) => { }, { res.json(notes) "id" : 3, }) "text" : "Go on vacation" , "done" : false } ] 16
/todos Enter text ... Add Do laundry Prepare talk ☐ Go on vacation Back-End API 17 17
/todos let todos = [...] Enter text ... Add app.patch('/todos/:id', (req, res) => { Do laundry const id = req.params.id const todo = todos Prepare talk .find(todo => todo.id === id) todo.done = !todo.done ☐ Go on vacation res.sendStatus(200) }) PATCH /todos/3 Back-End API 18 18
POST /todos {“text”: “Try Node.js”} /todos let todos = [...] Try Node.js Add // parse JSON from HTTP body Do laundry app.use(express.json()) Prepare talk app.post('/todos', (req, res) => { const todo = req.body Go on vacation todo.id = getNextId() todo.done = false todos.push(todo) res.json(todo) }) Back-End API 19 19
Middleware const express = require('express') const path = require('path') // serve static files from ./public Parsing ▣ app.use(express.static( path.join(__dirname, 'public') Routing ▣ order )) Static Files ▣ Error Handling ▣ /* request handlers */ Authentication ▣ // handle unmapped routes Logging ▣ app.use((req, res) => { res.status(404).send('Not Found') }) 20
Project Structure // install generator npm -g install express-generator // generate project express --view=ejs my-app Configures: Error handling ▣ View rendering ▣ Static files ▣ Cookie parsing ▣ Logging ▣ 21
{ package.json "name": "ijs-express", "version": "0.0.1", "scripts": { "start": "node index.js", "watch": "nodemon index.js", "start-ts: "ts-node index.ts" }, "dependencies": {...}, "devDependencies": { "nodemon": "^1.19.4", "ts-node": "^8.4.1" } } 22
Real World Node.js is a tool 23
Opportunities no context switch hiring Full Stack JS code sharing onboarding npm is deployment options biggest registry Ecosystem tool support community multitude of less concurrency requests concerns IO Performance connect downstream services 24
Challenges no typing architecture TypeScript NestJS Maintainability testing Jest Security audits package code injection corruption linting best practices CPU Performance worker threads 25
Use Cases Web Data-intensive Realtime Internet of Chat ▣ ▣ Server-side ▣ Things Gaming ▣ pages Streaming ▣ APIs ▣ You’re most effective with what you have - until you’re not 26
27 scenelab.io
Server-side Image Rendering Google Cloud Cloud SDK Storage JSON Raw fastify fs Images PNG JPG C++ Image sharp libvips Processing Node.js 28
Thumbnail Generation Cloud Function r e g g i r t upload image save thumbnail Cloud Storage 29
Thanks! Nils Mehlhorn freelance software engineer nils-mehlhorn.de @n_mehlhorn www @n_mehlhorn 30
Recommend
More recommend