<file_sep>/*
    server.js
    main server script for the socket.io chat demo
*/

var net = require('net');

//create a new network server
var server = net.createServer();

//array of connected clients
var clients = [];

server.on('connection', function(socket) {
    var name;

    function broadcast(name, message) {
        clients.forEach(function(client) {
            if (client !== socket) {
                client.write('[' + name + '] ' + message);
            }
        });
    }

    clients.push(socket);

    socket.write('Hello! What is your name?\n');

    socket.on('data', function(data) {
        if (!name) {
            name = data.toString().trim();
            socket.write('Hello ' + name + '!\n');
        } else {
            var message = data.toString();
            if (message.trim() === 'exit') {
                socket.end();
            } else {
                broadcast(name, data.toString());
            }

        }
    });
});

server.on('listening', function() {
    console.log('server listening on port 3000');
});

server.listen(3000);<file_sep># SQLite Database Directory

The first time our server starts up, it will create a SQLite database in this directory to store our data.

For more information about SQLite, see:

- [SQLite web site](https://www.sqlite.org/)
- [Node.js driver for SQLite](https://github.com/mapbox/node-sqlite3)
<file_sep>/*
    script file for the Tasks application
*/
angular.module('TasksApp', [])
    .controller('TasksController', function($scope, $http) {
        function handleApiError(err) {
            $scope.showSpinner = false;
            $scope.error = err;
        }

        $scope.newTask = {};

        $scope.showSpinner = true;
        $http.get('/api/tasks')
            .then(function(results) {
                $scope.showSpinner = false;
                $scope.tasks = results.data;
            }, handleApiError);

        $scope.addTask = function() {
            $scope.showSpinner = true;
            $http.post('/api/tasks', $scope.newTask)
                .then(function(results) {
                    $scope.showSpinner = false;
                    //new task object is returned, including new rowid
                    $scope.tasks.push(results.data);
                    $scope.newTask = {};
                }, handleApiError);
        }; //addTask()

        $scope.toggleDone = function(task) {
            var updateTask = angular.copy(task);
            updateTask.done = !updateTask.done;

            $scope.showSpinner = true;
            $http.put('/api/tasks/' + updateTask.rowid, updateTask)
                .then(function(results) {
                    $scope.showSpinner = false;
                    angular.copy(updateTask, task);
                }, handleApiError);
        };
    });<file_sep>/*
    server.js
    main server script for our task list web service
*/

var port = 8080;

//load all modules we need
//express web server framework
var express = require('express');
//sqlite library
var sqlite = require('sqlite3');
//body parser library
var bodyParser = require('body-parser');


//create a new express app
var app = express();

//tell express to server static files firom the /static subdir
app.use(express.static(__dirname + '/static'));

//tell express to parse post body to data as json
app.use(bodyParser.json());

//api route for getting tasks
app.get('/api/tasks', function(req, res, next) {
    var sql = 'select rowid,title,done,createdOn from tasks where done !=1';
    db.all(sql, function(err, rows) {
        if (err) {
            return next(err);
        }

        //send rows back to client as JSON
        res.json(rows);
    });
});

//when someone posts to /api/tasks...
app.post('/api/tasks', function(req, res, next) {
    var newTask = {
        title: req.body.title,
        done: false,
        createdOn: new Date()
    };

    var sql = 'insert into tasks(title,done,createdOn) values(?,?,?)';
    db.run(sql, [newTask.title, newTask.done, newTask.createdOn], function(err) {
        if (err) {
            return next(err);
        }

        res.status(201).json(newTask);
    });
});

//when someone PUTS to /api/<tasks/task-id>...
app.put('/api/tasks/:rowid', function(req, res, next) {
    var sql = 'update tasks set done=? where rowid=?';
    db.run(sql, [req.body.done, req.params.rowid], function(err) {
        if (err) {
            return next(err);
        }

        res.json(req.body);
    });
});

//create new database
var db = new sqlite.Database(__dirname + '/data/tasks.db', function(err) {
    if (err) {
        throw err;
    }

    var sql = 'create table if not exists tasks(title string, done int, createdOn datetime)';
    db.run(sql, function(err) {
        if (err) {
            throw err;
        }
    });

    //start the server
    app.listen(port, function() {
        console.log('server is listening on http://localhost:' + port);
    });

});

<file_sep># Instructions

This repo contains the starter files for my Intro to Node.js lecture. To get setup, please follow these steps.

1. [Fork this repo](https://help.github.com/articles/fork-a-repo/) into your own GitHub account
1. Clone your forked repo to your lab machine or personal computer
1. Open the project directory in your preferred editor

We will implement the server(s) together, and I will explain everything as I go along. 

# Viewing the Completed Version

To view the completed version of this exercise, switch to the `completed` branch by executing the following command from within your project directory. Note that if you have uncommitted changes, git will make you commit or stash them before you can checkout the other branch.

```bash
$ git checkout completed
```

To switch back to the master branch, execute this command:

```bash
$ git checkout master
```
