(Switch between modes with .pause() and .resume())
fsReadStream .pipe(compress) .pipe(encrypt) .pipe(fsWriteStream);
Complex example: Stream Playground
An entire build system built on pipes: Gulp
var f = function(chunk, enc, cb) {
var string = chunk.toString();
var upper = string.toUpperCase();
this.push(upper, enc);
cb();
};
MyTransform.prototype._transform = f;
function sleep(ms) {
var d = Q.defer();
setTimeout(function() {
d.resolve();
}, ms);
return d.promise;
}
sleep(1337).then(function() {
console.log('done! :3');
});
a1().then(function(val) {
return a2(val);
}).then(function(val) {
return a3(val);
}).then(function(val) {
console.log('done!');
}, function(err) {
console.log('err!');
});
try {
var v = a1();
v = a2(v);
v = a3(v);
console.log('done!');
} catch(e) {
console.log('err!');
}
with --harmony flags (or use gnode)
function* range(a, b) {
while(a < b) {
yield a++;
}
}
for(let i of range(2, 8)) {
console.log(i); //2, 3, 4, 5, 6, 7
}
Use yield to suspend execution, .next() to continue
magic(function* (resume) {
try {
var result = yield fs
.readFile('./existing.file', resume);
console.log(result);
var result2 = yield fs
.readFile('./missing.file', resume);
} catch(e) {
console.error(e);
}
});
function magic(f) {
var g = f(function(err, result) {
if(err) {
return g.throw(err);
}
g.next(result);
});
g.next();
}
Use a robust library, like co, galaxy, suspend, etc. They work with promises, can do basic control flow, etc...
The next version of express.js