CSE 154: Web Programming
Node.js/Express “Cheat Sheet”
This reference summarizes the most useful methods/properties used in CSE 154 for Nodejs/Express. Itis not an
exhaustive reference for everything in Node js/Express (for example, there exist many more fs
methods/properties than are shown below), but provide most functions/properties you will be using in this class.
Note that this Cheat Sheet is more comprehensive than the one provided in CSE154 exams.
Basic Node.js Project Structure
example-node-project/
-gitignore
APIDOC.md
app.is
node_modules/
package. json
public/
img/
index.html
index. js
styles.css
Example Express app Template
use strict";
/* File comment */
const express = require("express")
11 other modules you use
11 program constants
const app = express();
11 if serving front-end files in public/
app.use(express.static(*public"));
11 4 handling different POST formats
app.use(express.urlencoded({ extended: true }))
app-use (express. json());
‘app_use(multer() .none()) ;
11 app.get/app-post endpoints
11 helper functions
const PORT = process.env.PORT || 800%
app. Listen(PORT) ;
npm Commands
‘Command
Description
npm init
Initializes a node project. Creates packages|son to track required
modules/packages, as well as the node_modiules folder to track
Imported packages.
npm install
Installs any requirements for the local node package based on the
contents of package son.
pm install
Installs a package from NPM's own repository as well as any
requirements specified in that package's package,son fileGlossary
Term Definition
APL Application Programming Interface.
(Web Service ‘Atype of API that supports HTTP Requests, returning data such as
SON or plain text.
Express ‘A module for simplifying the htte-server core module In Node to
Implement APIs
pm The Node Package Manager. Used to initialize package json files
and install Node project dependencies.
Module {A standalone package which can be used to extend the
functionality of Node project.
Package Any project with a packagejson fle
‘API Documentation
Alle detalling the endpoints, usage, and functionality of various
endpoints of an APL
‘Server ‘A publicly accessible machine which exchanges information with
fone or mare clients at a time,
‘Client
{A private or public machine which requests information from @
Useful Core Modules
Module Description
fs The “file system” module with various functions to process data in the file system,
path Provides functions to process path strings.
util Provides various “utlty” functions, such as uti. promisiy.Other Useful Modules
The following modules must be installed for each new project using npm install .
Module Description
express ‘A module for simplifying the http-server core module In Node to implement APIs.
‘glob Allows for quick traversal and fitering of files in a complex directory
multer Used to support FormData POST requests on the server-side so we can access the req.body parameters,
mysql Provides functionality for interacting with a database and tables.
promise-mysql
Promisified wrapper over mysql module - each function in the mysql module returns a promise instead of|
taking a callback as the last argument (recommended),
cookie-parser
‘A module to access cookies with reqjres abjects in Express.
Express Route Functions
Function
Description
app.get("path”, middle
app.get("/*, (req, res) => ¢
vi
app.get(*/:eity", (req, res) => {
Tet city = req\parans.city;
we
app.get("/cityData, (req, res) => {
let city = req.query.city;
ni:
// Example with multiple middleware functions
app.get("/*, validatelnput, (req, res) => {
}, handleerr);
Defines a server endpoint which accepts a valig GET request
Request and response objects are passed as req and res.
respectively. Path parameters can be specified in path with
“-variame" and accessed via req. params. Query parameters
can be accessed via req. query.
‘app.post(“path”, middlewareFn(s));
app.post(“/additem, (req, res) => {
let itemName = req.body.nane;
Defines a server endpoint which accepts a valid POST request
Request and response objects are passed as req and res,
respectively. POST body is accessible via req.body. Requires
POST middleware and mutter module for FormData POST
request,Request Object Properties/Functions
Property/Function Description
req.parans Captures a dictionary of desired path parameters. Keys are
placeholder names and values are the URL itsel.
req.query Captures a dietionary of query parameters, specified in @
Pkeyt-valuedakey2-val ue28 ... pattern
req. body Holds @ dictionary of POST parameters as key/value pairs
Requires multer module for muttipart form requests (e.g.
FormData) an¢ using midsleware functions (see Express template)
for other POST request types.
req.cookies Rettieves all cookies sent in the request. Requires cookie-parser
module.
Response Object Properties/Functions
Property/Function Description
res.set(headerName, value);
Used to set different response headers -commenly the
“Contenttype” though there are others we don't cover).
res.set("Content-Type", “text/plain") ;
res set(“Content-Type", “application/ json");
res. type(“text”); Shorthand for seting the “Content-Type head
res. type(“json");
res. send(data) ; Sends the data back to the client, signaling an end to the
response (does not terminate your JS program)
res.send(“Hello") ° * prosram)
res.send({ “msg”! “Hello” })
res.end(); Ends the requestesponse cycle without any data (does
not terminate your JS program)
res. json(data); ‘Shorthand for setting the content type to JSON and
sending JSON
res. status(statusCode) Species the HTTP stats code of the response to
communicate success/fallure toa clent
res. status(492) .send(*client-side error message");
res.status(50) .send("server-side error message");Useful fs Module Functions
Note: You will often see the following “promisified” for use with async/await. The promisified versions will return
a Promise that resolves callback’s contents or rejects if there was an error. Remember that you should always
handle potential fs function errors (try/catch if async/await,if/else if standard callback)
Example of promisifying callback-version of fs.readFile
fs.readrile(*file.txt", “utfé", (err, contents)
Den
1) Promisified
const util = require(*util");
const readFile = util.promisify(fs.readFile) ;
{
asyne function example() (
try {
let contents = await readFile(*file.txt");
) eateh(err) {
>
}
Function
Description
fs.readFile(filename, ‘utf8", callback) ;
fs.readFile(*file.txt”, "utfe",
(err, contents) => (7... }
TH
Reads the contents ofthe file located at relative
directory filename, If successful, passes the fle
contents to the callback as contents parameter
Otherwise, passes error info to callback as error
parameter.
fe.writeFile(filenane, data, “utf@", callback);
fs.writeFile("file.txt", “new contents", “utfa",
(err) => ¢ )
vu
Writes data string to the file specified by filename,
overwriting is contents ii already exists, fan ervor
occurs, error is passed to the callback function,
fs.appendFile(filename, data, “utf8", callback);
fs.appendFile("file.txt", ‘added contents”, “utf8",
(err) = ... }
)
Writes data to the fle specified by Filename,
appending te its contents. Creates a new fle ifthe
filename does not exist. fan error occurs, error is
passed to the callback function
fs.
xistsSyne( filename) ;
Retums true ifthe given flename exists. This isthe
(the asynchronous function Is deprec
condltions),
fs.readdir(path, callback:
fs.readdir("dir/path”, (err, contents)
:
Retrieves all files within a drectory located at path. It
successful, passes the array of directory content
paths (as stings) to the callback as contents
parameter. Otherwise, passes error info to callback
as error parameterUseful path Module Functions
Function
Description
path. basename(pathStr) ;
Returns the flename of the pathStr. Ex. “picture.png" fr “imgfpicture.png*
path. extname(pathStr) ;
Returns the fle typeifle extension ofthe pathStr. x." png" for “img/pieture.png"
path. dirname(pathstr);
Returns the directory name of the pathSte. £x: "img!" for “img/picture.png”
The glob module
Function
Description
@lob(pattern, callback);
glod(“ing/+", (err, paths) => {
ni
J! promisified
paths = await glob(*img/4");
‘Globs all path strings matching a provided pattern. The pattern will generally
follow the structure ofa file path, along with any wildcards. fno paths match, the
result array willbe empty. Ifsuccessful, passes the array of directory content
paths (as stings) to the callback as contents parameter. Otherwise, passes error
info to callback as error parameter.
‘Common selectors:
A wildeard selector that will contextually maten a single filename, suffix, of
sirectory,
#*- 1 recursive selector that wil search into any subdirectories fo
follows it
patter that
The promise-mysql module
Function
Description
mysql.createConnection({
host
port : port,
password : pw,
database : dbname
YD:
hostname, // default localhost
Rotuns @ connected database object using config variables. Ifan
‘error occurs during connection (e.g. the SQL server Is not runing},
{oes not retuin 2 defined database object.
db.query(qryString) ;
db.query(qryString, [placeholders]) ;
Executes the SQL query Ifthe query Is a SELECT statement, returns a
Promise that resolves to an array of RowDataPackets withthe records
matching the qryString passed. I the query is an INSERT statement
the Promise resolves to an OkPacket, Throws an etrarf something
{goes wrong during the query
When using variables in your query string, you should use ?
placeholders in the string and populate [placeholders] with the
variable names to santtize the input against SAL injection