Skip to content

Instantly share code, notes, and snippets.

@nimbus154
Last active February 8, 2016 17:08
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 nimbus154/c88f6f0f058fc9ec5005 to your computer and use it in GitHub Desktop.
Save nimbus154/c88f6f0f058fc9ec5005 to your computer and use it in GitHub Desktop.
Using & testing coroutines in Node.js with co & tape
const bluebird = require('bluebird');
const co = require('co');
const fs = bluebird.promisifyAll(require('fs'));
const _ = require('lodash');
function lsPromise() {
return co(function* () {
let paths = { current: '.', root: '/' };
return yield _.mapValues(paths, path => fs.readdirAsync(path));
});
}
function lsCallback(cb) {
cb = cb || () => {};
return lsPromise()
.then(files => cb(null, files))
.catch(e => cb(e));
}
co(function* main() {
let files = yield lsPromise();
console.log('promise', files);
});
lsCallback((e, r) => {
if (e)
return console.log('error', e);
console.log('callback', r);
})
{
"name": "coroutines",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": ">=4"
},
"scripts": {
"start": "node --use_strict index",
"test": "node test"
},
"author": "nimbus154",
"license": "MIT",
"dependencies": {
"bluebird": "^3.2.2",
"co": "^4.6.0",
"lodash": "^4.2.1"
},
"devDependencies": {
"blue-tape": "^0.2.0"
}
}
const bluebird = require('bluebird');
const test = require('blue-tape');
const co = require('co');
const fs = bluebird.promisifyAll(require('fs'));
function ls(path) {
return co(function* () {
return yield fs.readdirAsync(path);
});
}
test('should exist', assert => {
return ls('.');
});
test('not exist', assert => {
return assert.shouldFail(ls('./not-a-directory'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment