Skip to content

Instantly share code, notes, and snippets.

@mannharleen
Last active June 9, 2019 02:50
Show Gist options
  • Save mannharleen/b6b0309217e2f24765d8b6681ed7e82b to your computer and use it in GitHub Desktop.
Save mannharleen/b6b0309217e2f24765d8b6681ed7e82b to your computer and use it in GitHub Desktop.
todo in nodejs.js
#### to run
node client.js
> only implemented help, add and ls commands
const EventEmitter = require("events");
const readline = require("readline");
let client = new EventEmitter();
const server = require('./server.js').server(client);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (line) => {
console.log("Client input > " + line)
commands = line.split(" ");
client.emit('command', commands[0], commands.slice(1))
});
server.on('reply', (reply) => {
console.log("Server reply > " + reply)
});
const EmitEmitter = require('events');
class Server extends EmitEmitter {
constructor(client) {
super();
this.tasks = {};
this.taskId = 1;
client.on("command", (command, args) => {
switch(command) {
case "help":
case "add":
case "ls":
case "del":
// this.emit('reply', "hi!")
this[command](args);
break;
default:
this.emit('reply', "Not a valid command. Type help for help");
}
});
};
getTasks() {
return Object.keys(this.tasks).map(key =>
key + " :> " + this.tasks[key]
// return `${key} : ${this.tasks[key]}`
).join('\n');
}
help() {
this.emit('reply', `Available commands are:
* help
* add <taskname>
* ls
* del <taskname>
`)
};
add(args) {
//add task
this.tasks[this.taskId] = args.join(' ');
this.taskId++;
this.emit('reply', `Task ${args.join(' ')} added`);
};
ls() {
this.emit('reply', `The list of tasks are:
${this.getTasks()}
`);
}
};
exports.server = (client) => new Server(client);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment