· 7 years ago · Nov 11, 2018, 10:24 PM
1// server.js
2// where your node app starts
3
4// init project
5var express = require('express');
6var bodyParser = require('body-parser');
7var app = express();
8app.use(bodyParser.urlencoded({ extended: true }));
9
10// we've started you off with Express,
11// but feel free to use whatever libs or frameworks you'd like through `package.json`.
12
13// http://expressjs.com/en/starter/static-files.html
14app.use(express.static('public'));
15
16// init sqlite db
17var fs = require('fs');
18var dbFile = './.data/sqlite.db';
19var exists = fs.existsSync(dbFile);
20var sqlite3 = require('sqlite3').verbose();
21var db = new sqlite3.Database(dbFile);
22
23// if ./.data/sqlite.db does not exist, create it, otherwise print records to console
24db.serialize(function(){
25 if (!exists) {
26 db.run('CREATE TABLE Dreams (dream TEXT)');
27 console.log('New table Dreams created!');
28
29 // insert default dreams
30 db.serialize(function() {
31 db.run('INSERT INTO Dreams (dream) VALUES ("Find and count some sheep"), ("Climb a really tall mountain"), ("Wash the dishes")');
32 });
33 }
34 else {
35 console.log('Database "Dreams" ready to go!');
36 db.each('SELECT * from Dreams', function(err, row) {
37 if ( row ) {
38 console.log('record:', row);
39 }
40 });
41 }
42});
43
44// http://expressjs.com/en/starter/basic-routing.html
45app.get('/', function(request, response) {
46 response.sendFile(__dirname + '/views/index.html');
47});
48
49// endpoint to get all the dreams in the database
50// currently this is the only endpoint, ie. adding dreams won't update the database
51// read the sqlite3 module docs and try to add your own! https://www.npmjs.com/package/sqlite3
52app.get('/getDreams', function(request, response) {
53 db.all('SELECT * from Dreams', function(err, rows) {
54 response.send(JSON.stringify(rows));
55 });
56});
57
58// listen for requests :)
59var listener = app.listen(process.env.PORT, function() {
60 console.log('Your app is listening on port ' + listener.address().port);
61});