Node Flashcards

(117 cards)

1
Q

initialize N project with standard defaults

A

npm init -y

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

initialize N project step by step

A

npm init

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

install W for a N server

A

npm i -D webpack webpack-cli _webpack-dev-server

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

run W in specific mode

A

webpack –mode=«mode»

» mode: none, developmen, production

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

name of standard W config file

A

webpack.config.js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

minimum W config

A
» webpack.config.js:
module.exports = {
  entry: '«entry filename/path»',
  mode: '«mode»',
  output: {
    filename: «output filename»,
    _path: «absolute output path»,
    _publicPath: «relative public path»
  }
}

» !module.exports
» mode: development, production, none
» path: path.resolve(__dirname, ‘«folder»’)
» dev server: needs both output AND public path

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

use current work directory path in N

A

import path from ‘path’

path.resolve(__dirname, ‘«relative path»’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

set path for public/asset and output bundle folder in W config

A

» output: {
publicPath: «path»
}

» path: relative to server root: ‘/«folder»/’
» path: relative to index.html: ‘«folder»/’, ‘../«folder»/’
» from index.html to output script

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

set serving root of development server in W config

A

» devServer: {
contentBase: «server root»
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

run W development server

A

webpack-dev-server

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

setup loader in W

A
» npm i -D «_package» «package loader»
» module > rules: [{
  test: «test regex»,
  use: ['«loader2»', '«loader1»']
}]

» right loader is first

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

show W dev server error in browser window

A

» devServer: {
overlay: true
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

setup CSS in W

A
» npm i -D css-loader style-loader
» module > rules: [{
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
}]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

setup HTML in W

A
» npm i -D html-loader extract-loader file-loader
» module > rules: [{
  test: /\.html$/,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[name].html'
      }
    },   // resolves import/require
    'extract-loader',   // resolves urls
    'html-loader'   // loads raw html
  ]
}]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

setup image load in W

A
» module > rules: [{
  test: /\.(jpg|jpeg|png|gif)$/,
  use: {
    loader: 'file-loader',
    options: {
      name: '«images folder»/[name].[ext]'
    }
  }
}]

» configured html-loader required

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

name of Babel configuration file

A

.babelrc

» is JSON file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

setup Babel in W

A
» npm i -D @babel/core @babel/preset-env babel-loader
» module > rules: [{
  test: /\.js$/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: ['@babel/preset-env']
    }
  },
  exclude: /node_modules/
}]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

setup minimal Express server in N

A

import express from ‘express’

const app = express()

app.listen(«port», () => {
console.log(Server is listening on port {«port»})
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

setup SASS in W

A
» npm i -D sass(/node-sass) sass-loader
» module > rules: [{
  test: /\.scss$/,
  use: ['style-loader', 'css-loader', 'sass-loader']
}]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

setup TypeScript in W

A
» npm i -D typescript ts-loader
» entry: './src/index.ts'
» resolve > extensions: [ _'.tsx', '.ts', '.js' ]
» module > rules: [{
  test: /\.tsx?$/,
  use: 'ts-loader',
  exclude: /node_modules/
}]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

setup plugin in W

A
» npm i -D «plugin»
» const «plugin» = require('«plugin»');
» plugins: [
  new «plugin»()
]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

setup code splitting in W

A

» optimization > splitChunks: {
chunks: ‘all’,
_minSize: 0
}

» reduces duplicate code and libraries

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

setup webpack-dev-server with hot reloading in W

A
» npm i -D webpack-dev-server
» const webpack = require('webpack')
» devServer: {
  hot: true
 }
» plugins: [
  new webpack.HotModuleReplacementPlugin()
]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

setup source mapping to original code for webpack-dev-server

A

» devtool: ‘(inline-)source-map’

» inline-: works in production

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
ES6 import of element from other file in N
import «default element alias» from './«file path»' import * as «alias» from './«file path»' import _«default element alias», { «element 1», «_element 2», _... } from './«file path»'
26
access file system in N
import fs from 'fs'
27
ES6 export of element from file in N
export _default «element» | export { «element» _as default, «_other element», _... }
28
install specific version of N package
npm i «package»@«version»
29
setup hot reloading on save of N
» npm i -D nodemon » package.json > scripts: nodemon «entry point»
30
get terminal arguments in N
process.argv » is JS array
31
transform buffer to string in N
«buffer».toString()
32
debug N in VSC and Chrome
» put «debugger» in code » run: node inspect «entry point» » restart application with «restart» in terminal
33
compare dart-sass to node-sass
» dart gets new features earliest » dart > node on cross platform » dart installs faster than node » dart runs slower than node
34
setup static assets folder in Express
app.use(express.static(«public folder path»))
35
set server setting in Express
app.set(«key», «value»)
36
create a mongodb client in N
import { MongoClient } from 'mongodb' MongoClient.connect(«url», «_options», (error, client) => { client... })
37
connect to a database with a mongodb client in N
const db = client.db(«database name»)
38
setup parsing of incoming json in Express
app.use(express.json())
39
access request parameters in Express
app.«http method»('«url»/:«param 1»', (req, res) => { req.params.«param 1»... })
40
setup get route in Express
app.get('«url»', (req, res) => { ... })
41
setup post route in Express
app.post('«url»', (req, res) => { ... })
42
setup router in Express
const router = express.Router() router. «route handler 1» router. «route handler 2» app.use('/«pre route»', router) » route handler: «http method»('«url»', (req, res) => { ... })
43
add middleware to Express server
app.use(«middleware»)
44
add middleware to Express route
``` app.«http method»( '«url»', «middleware», (req, res) => { ... } ) ```
45
access query parameters in Express
app.«http method»('«url»', (req, res) => { req.query... })
46
setup error handling for route in Express
``` app.«http method»('«url»', (req, res) => { // handle success }, (err, req, res, next) => { // handle error } ```
47
uninstall package in N
npm r «package» » also: remove, rm, un, uninstall, unlink
48
setup Socket.io on an Express server in N
import http from 'http' import express from 'express' import socketio from 'socket.io' ``` const app = express() const server = http.createServer(app) const io = socketio(server) ``` server.listen(«port», «callback»)
49
listen for Socket.io connection in N
io.on('connection', «callback»)
50
setup Socket.io in the client in N
``` ≤body≥ ... ≤script src="/socket.io/socket.io.js"≥≤/script≥ ≤script≥ io() ≤/script≥ ≤body≥ ```
51
send Socket.io event to »the« connected client in N
socket.emit(«event», «payload»)
52
listen for Socket.io events of a connection in N
socket.on(«event», «callback»)
53
send Socket.io event from server to »all« connected clients in N
io.emit(«event», «payload»)
54
send Socket.io event to »all« connected clients »except« the current ones in N
socket.broadcast.emit(«event», «payload»)
55
listen for when a Socket.io connection ends in N
socket.on('disconnect', «callback»)
56
acknowledge event in Socket.io in N
``` » sender: «io/socket».emit(«event», «payload», «ack callback») ---------- » receiver: «io/socket».on(«event», («payload», ack) => { ... ack() } ```
57
setup Babel script without Webpack in N
``` » npm i -D @babel/core @babel/preset-env » .babelrc: { "presets": ["@babel/preset-env"] } » package.json > scripts: "start": "babel-node «path to entry point»" ```
58
setup GQL API server with graphql-yoga in N
import { GraphQLServer } from 'graphql-yoga' » import context: db, ... » import resolvers: Query, Mutation, custom types ``` const server = new GraphQLServer({ typeDefs: '«path to schema»', resolvers: { «resolvers» }, context: { «context» } }) ``` server.start(«_options», «callback»)
59
what are the 5 scalar types in GQL?
``` » Boolean » Int » Float » String » ID ```
60
setup nodemon script with Babel in N
» package.json > scripts: | nodemon «entry point» --exec babel-node
61
setup plugin for Babel in N
» npm i -D «plugin» » .babelrc: { "plugins": ["«plugin»"] }
62
set input or return value to required in GQL schema in N
» schema.graphql: | ...«value»!
63
what are the 4 GQL resolver arguments?
» parent: parent element » args: client data » ctx: universal elements like db, ... » info: query fileds/path, fragments, ...
64
query data from GQL API
``` query { «object to return» { «_fields to return» } } ```
65
setup create, update or delete operation in GQL schema in N
``` » schema.graphql: type Mutation { «operation»( _id: ID!, «_payload label»: «payload type»! ): «return type»! } ```
66
create data with GQL API
``` mutation { «create function»( id: «id», «payload label»: «payload» ) { «values to return» } } ```
67
setup input type in GQL schema in N
``` » schema.graphql: input «input type» { «field 1»: «type 1», ... } ```
68
setup create, update or delete operation in GQL resolver in N
``` » resolvers > Mutation.js: const Mutation = { _async «operation»(parent, args, ctx, info) { // create, update or delete element return «element» } } ```
69
delete data with GQL API
``` mutation { «delete function»(id: «id») { «values to return» } } ```
70
update data with GQL API
``` mutation { «update function»( id: «id», «payload label»: «payload» ) { «values to return» } } ```
71
setup read operation in GQL schema in N
``` » schema.graphql: type Query { «element»( «_query arg 1»: «arg type 1», «_query arg 2»: «arg type 2» ): «return type»! } ```
72
setup enum in GQL schema in N
``` » schema.graphql: enum «name» { «value 1» «value 2» ... } ``` » values are strings » choose UPPERCASE values
73
setup server for GQL subscriptions with graphql-yoga in N
» index.js: import { GraphQLServer, PubSub } from 'graphql-yoga' const pubsub = new PubSub() ``` const server = new GraphQLServer({ ..., context: { pubsub } }) ``` server.start(«_options», «callback»)
74
setup subscription in GQL schema in N
``` » schema.graphql: type Subscription { «subscription name»( «_subscription arg»: «arg type» ): «return type»! } ```
75
setup resolver for GQL subscription in N
``` » resolvers > Subscription.js: const Subscription = { «subscription name»: { subscribe(parent, args, { pubsub }, info) { ... return pubsub.asyncIterator('«subscription channel»') } } } ```
76
publish to GQL subscription channel in N
``` » resolvers > Mutation.js: const Mutation = { «mutation function»(parent, args, { pubsub }, info) { ... pubsub.publish('«subscription channel»', { «subscription name»: { «fields and payload» } }) } } ```
77
create hash in N
import bcrypt from 'bcryptjs' const hash = await bcrypt.hash(«input», «salt») » recommended salt: 14
78
create JWT in N
import jwt from 'jsonwebtoken' ``` const token = jwt.sign( «input object», «secret», «_options», «_callback» ) ``` » options: { expiresIn: '7d', '10h', '120' } // ms » options: { algorithm: 'HS256' } // is default » callback: (err, token) => { ... } // makes it async
79
decode JWT token in N
import jwt from 'jsonwebtoken' const content = jwt.decode(«token»)
80
verify JWT in N
import jwt from 'jsonwebtoken' ``` const content = jwt.verify( «token», «secret», «_options», «_callback» ) ``` » throws error if invalid » options: { algorithms: ['HS256', 'HS384'] } » callback: (err, decoded) => { ... } // makes it async
81
check hash in N
import bcrypt from 'bcryptjs' await bcrypt.compare(«input», «hash») » true or false
82
setup script using local environment variables in N
» npm i -D env-cmd » package.json > scripts: env-cmd _-f «_path to env file» «command» » .env is default file
83
setup Jest test suite in N
``` » npm i -D jest » tests > «suite name».test.js: test(«test name», () => { ... expect(«variable»).«assertion»_(«target value») }) ```
84
configure scripts to run before Jest test run in N
``` » package.json: "jest": { "globalSetup": "«path to setup file»" "globalTeardown": "«path to teardown file»" } ```
85
setup start of db server before Jest test run in N
» global setup file: _require('babel-register') _require('@babel/polyfill/noConflict') const server = «import db server» module.exports = async () => { global.«db server name» = await server.«start»( ... ) } » no ES6 syntax yet » must be async function » might need babel-register and polyfill
86
setup stop of db server after Jest test run in N
» global teardown file: _require('babel-register') _require('@babel/polyfill/noConflict') module.exports = async () => { global.«db server name».«stop»() } » no ES6 syntax yet » must be async function » might need babel-register and polyfill
87
setup SASS to CSS compilation script in watch mode in N
» npm i -D node-sass » package.json > scripts: node-sass «input path» «output path» -w
88
setup SASS to CSS compilation script in N
» npm i -D node-sass » package.json > scripts: node-sass «input» «output»
89
setup CSS concatenation script in N
» npm i -D concat » package.json > scripts: concat -o «output» «input 1» «input 2» ...
90
setup CSS autoprefixing script in N
» npm i -D autoprefixer postcss-cli » package.json > scripts: postcss -u autoprefixer -b '«browserslist»' «input» -o «output» » browserlist: defaults, last 2 versions, ...
91
setup CSS compression script in N
» npm i -D node-sass » package.json > scripts: node-sass «input» «output» --output-style compressed
92
setup N scripts to run sequentially
» npm i -D npm-run-all » package.json > scripts: npm-run-all «script 1» «script 2» ...
93
setup N scripts to run at the same time
» npm i -D npm-run-all » package.json > scripts: npm-run-all --parallel «script 1» «script 2» ...
94
write middleware in Express in N
const «middleware» = (req, res, next) => { ... next() }
95
setup payload for query, mutation or subscription in GQL schema in N
``` » schema.graphql: type «Query|Mutation|Subscription» { «element»( «payload label»: «payload type» ): «return type» } ```
96
access payload for query or mutation in GQL resolver in N
``` » resolvers > «Query|Mutation».js: const «Query|Mutation» = { _async «element»(parent, args, ctx, info) { ...args.«arg 1» ... } } ```
97
setup relationship in GQL schema in N
» schema.graphql: type «custom type 1» { «field»: «custom type 2»|[«custom type 2»] }
98
setup relationship in GQL resolver in N
``` » resolvers > «custom type 1».js: const «custom type 1» = { «field»(parent, args, ctx, info) { ...parent return «custom type 2»|[«custom type 2»] } } ```
99
setup custom type in GQL schema in N
» schema.graphql: type «custom type» { «field»: «type» }
100
setup nodemon script to watch specific file extensions
» package.json > scripts: | nodemon «entry point» --ext js,«extention 1»,...
101
use reusable field selection for GQL API
``` query/mutation/subscription { «object to return» { «_fields to return» ...«selection name» } } ```
102
setup Apollo client in N
import { ApolloClient, InMemoryCache } from '@apollo/client'; ``` const client = new ApolloClient({ uri: '«host uri»', _link: «_link array», cache: new InMemoryCache() }) ```
103
run Jest test suite in N
jest _--watch
104
query/mutate data with external variables from GQL API
``` query/mutation «operation name»( $«variable»: «var type», ... ){ «object to return»(«arg name»: $«variable», ...) { «_fields to return» } } ```
105
write GQL query for Apollo client in N
import { gql } from '@apollo/client' const query = gql` «GQL query» `
106
execute GQL query in Apollo client in N
_await client.query({ query: «GQL query» })
107
execute GQL query with variable(s) in Apollo client in N
_await client.query({ query: «GQL query», variables: { «var 1»: «val 1» } })
108
execute GQL mutation in Apollo client in N
_await client.mutate({ mutation: «GQL query» })
109
execute GQL mutation with variable(s) in Apollo client in N
_await client.mutate({ mutation: «GQL query», variables: { «var 1»: «val 1» } })
110
execute GQL subscription in Apollo client in N
_await client.subscribe({ query: «GQL query» })
111
non-ES6 import of element from other file in N
const «default element alias» = require('./«file path»') | const «sub element alias» = require('./«file path»').«sub element»
112
non-ES6 export of element from file in N
module. exports = «element» | module. exports = { «element 1», «element 2» }
113
transform buffer to json in N
«buffer».toJSON()
114
define reusable field selection for GQL API
``` fragment «selection name» on «custom type» { «_field 1» «_relation 1» { } ... } ```
115
run W compilation
webpack
116
run W compilation in watch mode
webpack --watch
117
setup hot reloading for N backend server
» npm i -D clean-webpack-plugin webpack-node-externals » webpack.config.json: entry: entry: ['webpack/hot/poll?1000', «entry point»], externals: [ nodeExternals({ allowlist: ['webpack/hot/poll?1000'] }) ], plugins: [ new CleanWebpackPlugin(), new webpack.HotModuleReplacementPlugin() ] ``` » node entry point: if (module.hot) { module.hot.accept() module.hot.dispose(() => { /* stop server */ }) } ```