With Node.js we can use a variety of database engines such as MySQL, Postgres, MongoDB, and so on.
nedb is a MongoDB compatible in memory or on disk datastore that is quick and easy for us to work with without going through a big setup process so let's get a start with databases there.
In order to use it, we have to install it as we would any normal server side node module:
npm install nedb
// Database to store data, don't forget autoload: true var Datastore = require('nedb'); var db = new Datastore({filename: "data.db", autoload: true}); // Create a JavaScript Object with data to store var datatosave = { name: "Shawn", message: "Hello world" }; // Insert the data into the database db.insert(datatosave, function (err, newDocs) { console.log("err: " + err); console.log("newDocs: " + newDocs); }); // Find all of the existing docs in the database db.find({}, function(err, docs) { // Loop through the results, send each one as if it were a new chat message for (var i = 0; i < docs.length; i++) { console.log(docs[i].name + " " + docs[i].message); } });
As we have experienced, generating HTML within a node.js/Express server can be painful. Fortunately, there is a solution called templates which allow you to create your HTML as a separate file and have the Express template system bind data to your variables.
There are a plethora templating systems, many of which are cross-platform (moustache) and/or inspired by other platforms (jade/pug). These unfortunately are either complex to setup or require that you learn another language for authoring HTML. Fortunately, there is one system, ejs (embedded JavasScript) which allows regular HTML authoring with the ability to insert simple JavaScript statements which get run on the server side.
The first step to using ejs with Express is to install the module:
npm install ejs
To use ejs in our express app, we set the "view engine" to be "ejs" and then create a template to use
app.set('view engine', 'ejs');Here is a basic template:
<!DOCTYPE html> <html lang="en"> <body> <h1>My Cool Page</h1> <% if (person) { %> <h2><%= person.name %><h2> <h3><%= person.other %></h3> <% } %> </body> </html>save it as "template.ejs" inside a folder called "views" which is the default.
Then to use a template as the response to a request we do the following:
app.get('/templatetest', function(req, res) { var data = {person: {name: "Shawn", other: "blah"}}; res.render('template.ejs', data); });The "render" function takes in the template file and binds the "data" to it. Of course, the "data" can be any data.
To render an array of data:
var data = {people: [{name: "Shawn", other: "blah"}, {name: "Joe", other: "No"}]};you can use a "forEach" in the template:
<% people.forEach(function(person) { %> <h2><%= person.name %><h2> <h3><%= person.other %></h3> <% }); %>
More Information: Templating with EJS
CSS has a rich support for type or text formatting. Here are a few of the capabilities:
font-family: Times, serif; - Web Safe Fonts
Elements can be positioned in a number of ways in CSS.
A class of CSS layouts has appeared called grids. These are starting points for grid based layouts and easier to use that building from scratch. One of the most well known is the 960 Grid which is a 960 pixel wide grid based layout.
To use it, you download and included it on your page:
<link rel="stylesheet" type="text/css" href="960_12_col.css" />The above version is the 12 column version.
You specify in your block elements how many columns they should occupy in any given row:
<div class="container_12 clearfix"> <div class="grid_12">All 12 Columns</div> <div class="grid_4">4 Columns</div> <div class="grid_3">3 Columns</div> </div>
HTML & CSS by Jon Duckett is a fantastic book that takes you through a lot of how to work with HTML and CSS to make sites look the way you want. I highly recommend it.
HTML creates a document, JavaScript can access that document through a data structure called the DOM (or Document Object Model). This structure allows us to access each individual element as an object with a parent/child relationship or directly by ID:
var thediv = document.getElementById('mydiv'); thediv.innerHTML = "soemthing else";
Some things that you might want to look over: visibility and createElement and appendChild
Using the DOM, you can manipulate any aspect of an HTML Element, including it's CSS derived styles:
var thediv = document.getElementById('mydiv'); thediv.style.backgroundColor = "red";
JavaScript in the browser is very often event driven. This means that we can specify code to run when an event takes place. Some of these are driven by the browser doing it's thing such as loading a page and some are driven by user interaction such as clicking a link or hovering over an element. Regardless of the type of event, we use the "addEventListener" method on all of the DOM elements to specify what to listen for and what code to run when the event is triggered.
element.addEventListener('event name', functionToRun); functionToRun() { // Code to execute }JavaScript HTML DOM EventListener
The load event is very important as it is a way to specify what to do when a document is done loading, it also signifies when it is safe to call elements on the DOM:
function init() { var thediv = document.getElementById('mydiv'); alert(thediv.innerHTML); } window.addEventListener('load', init);
var thediv; function init() { thediv = document.getElementById('mydiv'); thediv.addEventListener('mouseover', hideit); } function hideit() { thediv.style.visibility = "hidden"; } window.addEventListener('load', init);