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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
var fs = require('fs');
var os = require('os');
var path = require('path');
var is = require('./is');
var IS_SUPPORT;
var TEMP_DIR = os.tmpdir && os.tmpdir()
|| process.env.TMPDIR
|| process.env.TEMP
|| process.cwd();
function TempStack() {
this.stack = [];
}
TempStack.prototype = {
create: function(type, base) {
var name = path.join(base,
'node-watch-' + Math.random().toString(16).substr(2)
);
this.stack.push({ name: name, type: type });
return name;
},
write: function(/* file */) {
for (var i = 0; i < arguments.length; ++i) {
fs.writeFileSync(arguments[i], ' ');
}
},
mkdir: function(/* dirs */) {
for (var i = 0; i < arguments.length; ++i) {
fs.mkdirSync(arguments[i]);
}
},
cleanup: function(fn) {
try {
var temp;
while ((temp = this.stack.pop())) {
var type = temp.type;
var name = temp.name;
if (type === 'file' && is.file(name)) {
fs.unlinkSync(name);
}
else if (type === 'dir' && is.directory(name)) {
fs.rmdirSync(name);
}
}
}
finally {
if (is.func(fn)) fn();
}
}
};
var pending = false;
module.exports = function hasNativeRecursive(fn) {
if (!is.func(fn)) {
return false;
}
if (IS_SUPPORT !== undefined) {
return fn(IS_SUPPORT);
}
if (!pending) {
pending = true;
}
// check again later
else {
return setTimeout(function() {
hasNativeRecursive(fn);
}, 300);
}
var stack = new TempStack();
var parent = stack.create('dir', TEMP_DIR);
var child = stack.create('dir', parent);
var file = stack.create('file', child);
stack.mkdir(parent, child);
var options = { recursive: true };
var watcher;
try {
watcher = fs.watch(parent, options);
} catch (e) {
if (e.code == 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM') {
return fn(IS_SUPPORT = false);
} else {
throw e;
}
}
if (!watcher) {
return false;
}
var timer = setTimeout(function() {
watcher.close();
stack.cleanup(function() {
fn(IS_SUPPORT = false);
});
}, 200);
watcher.on('change', function(evt, name) {
if (path.basename(file) === path.basename(name)) {
watcher.close();
clearTimeout(timer);
stack.cleanup(function() {
fn(IS_SUPPORT = true);
});
}
});
stack.write(file);
}
|