UNPKG

2.73 kBJavaScriptView Raw
1/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true*/
2(function () {
3 "use strict";
4
5 // "FIFO" isn't easy to convert to camelCase and back reliably
6 var isFnodeTypes = [
7 "isFile", "isDirectory", "isSymbolicLink", "isBlockDevice", "isCharacterDevice", "isFIFO", "isSocket"
8 ],
9 fnodeTypes = [
10 "file", "directory", "symbolicLink", "blockDevice", "characterDevice", "FIFO", "socket"
11 ],
12 fnodeTypesPlural = [
13 "files", "directories", "symbolicLinks", "blockDevices", "characterDevices", "FIFOs", "sockets"
14 ];
15
16
17 //
18 function createNodeGroups() {
19 var nodeGroups = {};
20 fnodeTypesPlural.concat("nodes", "errors").forEach(function (fnodeTypePlural) {
21 nodeGroups[fnodeTypePlural] = [];
22 });
23 return nodeGroups;
24 }
25
26
27 // Determine each file node's type
28 //
29 function sortFnodesByType(stat, fnodes) {
30 var i, isType;
31
32 for (i = 0; i < isFnodeTypes.length; i += 1) {
33 isType = isFnodeTypes[i];
34 if (stat[isType]()) {
35 stat.type = fnodeTypes[i];
36 fnodes[fnodeTypesPlural[i]].push(stat);
37 return;
38 }
39 }
40 }
41
42
43 // Get the current number of listeners (which may change)
44 // Emit events to each listener
45 // Wait for all listeners to `next()` before continueing
46 // (in theory this may avoid disk thrashing)
47 function emitSingleEvents(emitter, path, stats, next, self) {
48 var num = 1 + emitter.listeners(stats.type).length + emitter.listeners("node").length;
49
50 function nextWhenReady(flag) {
51 if (flag) {
52 stats.flag = flag;
53 }
54 num -= 1;
55 if (0 === num) { next.call(self); }
56 }
57
58 emitter.emit(stats.type, path, stats, nextWhenReady);
59 emitter.emit("node", path, stats, nextWhenReady);
60 nextWhenReady();
61 }
62
63
64 // Since the risk for disk thrashing among anything
65 // other than files is relatively low, all types are
66 // emitted at once, but all must complete before advancing
67 function emitPluralEvents(emitter, path, nodes, next, self) {
68 var num = 1;
69
70 function nextWhenReady() {
71 num -= 1;
72 if (0 === num) { next.call(self); }
73 }
74
75 fnodeTypesPlural.concat(["nodes", "errors"]).forEach(function (fnodeType) {
76 if (0 === nodes[fnodeType].length) { return; }
77 num += emitter.listeners(fnodeType).length;
78 emitter.emit(fnodeType, path, nodes[fnodeType], nextWhenReady);
79 });
80 nextWhenReady();
81 }
82
83 module.exports = {
84 emitNodeType: emitSingleEvents,
85 emitNodeTypeGroups: emitPluralEvents,
86 isFnodeTypes: isFnodeTypes,
87 fnodeTypes: fnodeTypes,
88 fnodeTypesPlural: fnodeTypesPlural,
89 sortFnodesByType: sortFnodesByType,
90 createNodeGroups: createNodeGroups
91 };
92}());