Skip to content

created Promises, event listeners and file operations #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,26 @@
# assignment_async_nodejs
Async Node.js sprint
# Building with Async Node.js (promises, event emitter...)

I this project I built promise-based interfaces. I used promises to write promise based versions of common Node.js fs module functions. Finally, `emitter.js` I created my own implementation of the Node.js EventEmitter and implemented it so it can be switched out with the core Node.js version!



## Getting Started

If you have [installed node](https://nodejs.org/en/download/) on your computer, type the following commands

```
$ node example.js
```

If you want to check statistics of other users run also the following lines after:



## Authors

* **Dariusz Biskupski** - *Initial work* - https://dariuszbiskupski.com


## Acknowledgments

This assignment is created for [Viking Code School](https://www.vikingcodeschool.com/)
1 change: 1 addition & 0 deletions data/lorem.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
1 change: 1 addition & 0 deletions data/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello!Hello again!
21 changes: 21 additions & 0 deletions emitter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// var Emitter = require('./event');

var Emitter = require('events');
var emitter = new Emitter();

var callback1 = function callback1() {
console.log('The first event occured!');
}

var callback2 = function callback2() {
console.log('A second Event!!');
}
emitter.on('event', callback1 )
.on('event', callback2 );
emitter.emit('event');

emitter.removeListener('event', callback1 );
console.log(emitter);

emitter.removeAllListeners('event');
console.log(emitter);
33 changes: 33 additions & 0 deletions event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

var Emitter = function() {
this._events ={};
this.on = function (eventType, callback) {
if (this._events[eventType]) {
this._events[eventType].push(callback);
} else {
this._events[eventType] = [callback];
}
return this;
};
this.emit = function(eventType) {
this._events[eventType].forEach( function(callback) {
return callback();
})
};
this.removeListener = function(eventType, callback) {
var idx;
this._events[eventType].forEach( function(callback_iter, index) {
if (callback_iter === callback) {
idx = index
}
})
this._events[eventType].splice(idx, 1);
};
this.removeAllListeners = function(eventType) {
delete this._events[eventType];
}
}



module.exports = Emitter;
31 changes: 31 additions & 0 deletions file_op.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

var fsp = require('./fsp');

fsp.readFile('./data/lorem.txt')
.then(function(data) {
// Outputs the file data
console.log(data);
})
.catch(function(err) {
console.error(err);
});

fsp.writeFile('./data/test.txt', 'Hello!')
.then(function(res) {
// Outputs the file data
// after writing
console.log(res);
})
.catch(function(err) {
console.error(err);
});

fsp.appendFile('./data/test.txt', 'Hello again!')
.then(function(res) {
// Outputs the file data
// after appending
console.log(res);
})
.catch(function(err) {
console.error(err);
});
38 changes: 38 additions & 0 deletions fsp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@

var fs = require('fs');

//
// fsp.writeFile('./data/test.txt', 'Hello!')
// .then(function(res) {
// // Outputs the file data
// // after writing
// console.log(res);
// })
// .catch(function(err) {
// console.error(err);
// });

module.exports = {
readFile: function (path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
err ? reject(err) : resolve(data);
})
})
},
writeFile: function (path, text) {
return new Promise((resolve, reject) => {
fs.writeFile(path, text,'utf8', (err, data) => {
err ? reject(err) : resolve(data);
})
})
},
appendFile: function (path, text) {
return new Promise((resolve, reject) => {
fs.appendFile(path, text, 'utf8', (err, data) => {
err ? reject(err) : resolve(data);
})
})
}

};
19 changes: 19 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "assignment_async_nodejs",
"version": "1.0.0",
"description": "Async Node.js sprint",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Visiona/assignment_async_nodejs.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/Visiona/assignment_async_nodejs/issues"
},
"homepage": "https://github.com/Visiona/assignment_async_nodejs#readme"
}
84 changes: 84 additions & 0 deletions promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@

var p = Promise.resolve("Hello Promise!");

p.then( function(message) {
console.log(message);
});


var delay = function(milliseconds) {
return new Promise((resolve) => {
setTimeout(function() {
resolve(milliseconds);
}, milliseconds);
});
}

function countDown (message) {
console.log(message);
return message - 100;
}

var square = function(number) {
return new Promise((resolve, reject) => {
resolve(number * number);
if (number == undefined) {
reject('No Number');
}
});
}

var int = [1,2,3,4,5,6,7,8,9];
var num = int.map( function(i) {
return square(i);
})

Promise.all(num).then(function(results) {
console.log(results);
})

var doBadThing = function(forRealz){
return new Promise((resolve, reject) => {
if (forRealz == false) {
resolve('Yay');
} else {
reject('rejected');
}
});
}

doBadThing(4).then( function(result) {
console.log(result);
})
.catch( function(err){
console.error(err);
});

doBadThing(true).then(function() {
console.log('I am falsy');
}, function() {
console.error('I am truthy');
})

doBadThing(0).then( function(result) {
console.log(result);
throw "Boom Boom Boom! Finito!!";
})
.catch( function(err){
console.error(err);
});



delay(1000)
.then(countDown) //=> 1000
.then(countDown) //=> 900
.then(countDown) //=> 800
.then(countDown) //=> 700
.then(countDown) //=> 600
.then(countDown) //=> 500
.then(countDown) //=> 400
.then(countDown) //=> 300
.then(countDown) //=> 200
.then(countDown) //=> 100
.then(countDown);