Created
November 7, 2013 03:22
-
-
Save dlmanning/7348450 to your computer and use it in GitHub Desktop.
Sample code for a PCS exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var read = require('read'); | |
var myBook = []; | |
var data = fs.readFileSync(__dirname + '/data.json', { encoding: 'utf8', flag: 'a+' }); | |
if (data) { | |
myBook = JSON.parse(data); | |
} | |
mainPrompt(); | |
var commands = { | |
"exit": exit, | |
"list": list, | |
"help": help, | |
"add": addContact | |
} | |
function mainPrompt () { | |
read({ prompt: '> '}, function (err, result) { | |
if (commands.hasOwnProperty(result)) { | |
commands[result](); | |
} else { | |
console.log("Invalid Command"); | |
mainPrompt(); | |
} | |
}); | |
} | |
// commands | |
function help () { | |
console.log("You can type: add, list or exit."); | |
mainPrompt(); | |
} | |
function addContact () { | |
var name, address, phone = ""; | |
read({ prompt: 'Enter name >' }, getName); | |
function getName (err, result) { | |
name = result; | |
read({ prompt: 'Enter address >' }, getAddress); | |
} | |
function getAddress (err, result) { | |
address = result; | |
read({ prompt: 'Enter phone >' }, getPhone); | |
} | |
function getPhone (err, result) { | |
phone = result; | |
addToBook(); | |
} | |
function addToBook () { | |
myBook.push({name: name, address: address, phone: phone}); | |
mainPrompt(); | |
} | |
} | |
function exit () { | |
saveMyData(); | |
console.log("See yah!"); | |
process.exit(); | |
} | |
function list () { | |
myBook.forEach(function (item) { | |
console.log(item); | |
}); | |
mainPrompt(); | |
} | |
// File I/O | |
function saveMyData () { | |
fs.writeFileSync(__dirname + '/data.json', JSON.stringify(myBook, null, '\t')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment