Skip to content

Instantly share code, notes, and snippets.

@dlmanning
Created November 7, 2013 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlmanning/7348450 to your computer and use it in GitHub Desktop.
Save dlmanning/7348450 to your computer and use it in GitHub Desktop.
Sample code for a PCS exercise
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