-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
69 lines (56 loc) · 1.43 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
var through = require('through2')
var from = require('new-from')
var bl = require('bl')
module.exports = map
function map(fn) {
var done = false
var pending = 0
var stream
return stream = through.obj(write, flush)
function write(file, _, next) {
if (typeof file !== 'object') return
if (!('contents' in file)) return push(file, next)
if (file.isNull()) return push(file, next)
if (file.isBuffer()) return map(file, next)
// should be a stream by
// this point...
pending++
file.contents.pipe(bl(function(err, result) {
if (err) return stream.emit('error', err)
map(file, next, result)
check(--pending)
}))
}
function map(file, next, contents) {
file = file.clone()
contents = arguments.length < 3
? file.contents
: contents
try {
var mapped = fn(contents, file.path)
} catch(err) {
return stream.emit('error', err)
}
if (mapped === undefined) mapped = contents
if (file.isBuffer()) file.contents = new Buffer(mapped)
if (file.isStream()) file.contents = from([mapped])
push(file, next)
}
function push(file, next) {
stream.push(file)
next()
}
function flush() {
check(done = true)
}
function check() {
if (!pending && done) {
process.nextTick(function() {
stream.emit('end')
process.nextTick(function() {
stream.emit('close')
})
})
}
}
}