Node.js and Express: A Lightweight Minimalist Framework

Getting Started

const express = require(“express”);
var request = require(“request”);
const app = express();
const port = 3001
app.get("/fruits", (req, res) => {
request("https://fruityvice.com/api/fruit/all",
function(error, response, body) {
if (!error && response.statusCode == 200) {
var parsedBody = JSON.parse(body);
res.send(parsedBody);
}
})
});
app.listen(port, () => {
console.log(`starting on ${port}`);
});
$node app.js

The Global Object

Modules

Implementation


require(‘path-of-file’)

The Events Module


const EventEmitter = require(‘events’) // a class
const emitter = new EventEmitter(); //an actual object, or an instant of the class EventEmitter
//Register a listener
emitter.on(‘messageLogged’, function(arg){. // or e
console.log(‘Listener called’);
});
//or ECMA6 syntax with arrow function:
emitter.on(‘messageLogged’, (arg) => {
console.log(‘Listener called’);
});
//Raise an event
emitter.emit(‘messageLogged, {id: 1, url: ‘http://..’});
//emit means producing a noise, signaling.
//Order matters. the listener must be defined before raising the event.//Raise: logging (data: message)

Working with Express: A Lightweight Minimalist Framework

$node i -D nodemon

Basic Routing

app.METHOD(PATH, HANDLER)
app.get('/', function (req, res) {
res.send('Hello World!')
})

Template Engines

app.set('view engine', ejs)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kristin Ponsonby

Kristin Ponsonby

Software engineer and advocate for women in STEM.