1var test = require('tape') 2var path = require('path') 3var from = require('./') 4var fs = require('fs') 5 6var tmp = path.resolve( 7 __dirname, 'tmp.txt' 8) 9 10function fromString(string) { 11 return from(function(size, next) { 12 if (string.length <= 0) return next(null, null) 13 var chunk = string.slice(0, size) 14 string = string.slice(size) 15 next(null, chunk) 16 }) 17} 18 19test('from2', function(t) { 20 var contents = fs.readFileSync(__filename, 'utf8') 21 var stream = fromString(contents) 22 23 stream 24 .pipe(fs.createWriteStream(tmp)) 25 .on('close', function() { 26 t.equal(fs.readFileSync(tmp, 'utf8'), contents) 27 fs.unlinkSync(tmp) 28 t.end() 29 }) 30}) 31 32test('old mode', function(t) { 33 var contents = fs.readFileSync(__filename, 'utf8') 34 var stream = fromString(contents) 35 var buffer = '' 36 37 stream.on('data', function(data) { 38 buffer += data 39 }).on('end', function() { 40 t.equal(buffer, contents) 41 t.end() 42 }) 43}) 44 45test('destroy', function(t) { 46 var stream = from(function(size, next) { 47 process.nextTick(function() { 48 next(null, 'no') 49 }) 50 }) 51 52 stream.on('data', function(data) { 53 t.ok(false) 54 }).on('close', function() { 55 t.ok(true) 56 t.end() 57 }) 58 59 stream.destroy() 60}) 61 62test('arrays', function (t) { 63 var input = ['a', 'b', 'c'] 64 var stream = from(input) 65 var output = [] 66 stream.on('data', function (letter) { 67 output.push(letter.toString()) 68 }) 69 stream.on('end', function () { 70 t.deepEqual(input, output) 71 t.end() 72 }) 73}) 74 75test('obj arrays', function (t) { 76 var input = [{foo:'a'}, {foo:'b'}, {foo:'c'}] 77 var stream = from.obj(input) 78 var output = [] 79 stream.on('data', function (letter) { 80 output.push(letter) 81 }) 82 stream.on('end', function () { 83 t.deepEqual(input, output) 84 t.end() 85 }) 86}) 87 88 89test('arrays can emit errors', function (t) { 90 var input = ['a', 'b', new Error('ooops'), 'c'] 91 var stream = from(input) 92 var output = [] 93 stream.on('data', function (letter) { 94 output.push(letter.toString()) 95 }) 96 stream.on('error', function(e){ 97 t.deepEqual(['a', 'b'], output) 98 t.equal('ooops', e.message) 99 t.end() 100 }) 101 stream.on('end', function () { 102 t.fail('the stream should have errored') 103 }) 104}) 105 106test('obj arrays can emit errors', function (t) { 107 var input = [{foo:'a'}, {foo:'b'}, new Error('ooops'), {foo:'c'}] 108 var stream = from.obj(input) 109 var output = [] 110 stream.on('data', function (letter) { 111 output.push(letter) 112 }) 113 stream.on('error', function(e){ 114 t.deepEqual([{foo:'a'}, {foo:'b'}], output) 115 t.equal('ooops', e.message) 116 t.end() 117 }) 118 stream.on('end', function () { 119 t.fail('the stream should have errored') 120 }) 121}) 122 123 124