-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs-promised.js
94 lines (84 loc) · 2.55 KB
/
fs-promised.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
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
/*jshint laxbreak:true*/
"use strict";
var fs = require('fs')
, D = require('d.js')
, methods = (
'rename,ftruncate,truncate,chown,fchown,lchown,chmod,fchmod,lchmod,stat,lstat,fstat,link,symlink,readlink,realpath'
+ ',unlink,rmdir,mkdir,readdir,close,open,utimes,futimes,fsync,write,read,readFile,writeFile,appendFile'
).split(',')
;
methods.forEach(function(m){
fs[m + 'Promise'] = D.nodeCapsule(fs, fs[m]);
});
//----- NON STANDARD METHODS -----//
fs.existsPromise = function(path){
var d = D();
fs.exists(path, d.resolve);
return d.promise;
};
//----- JSON RELATED METHODS -----//
fs.readJsonSync = function readJsonSync(filename, options){
if( options && !options.encoding ){
options.encoding='utf8';
}
var data = fs.readFileSync(filename, options || 'utf8');
return JSON.parse(data);
};
fs.readJsonPromise = function readJsonPromise(filename, options){
return fs.readFilePromise(filename, options).success(JSON.parse);
};
function stringify(data, options){
var replacer = options && options.replacer || null
, space = options && options.space || '\t'
;
return JSON.stringify(data, replacer, space);
}
fs.writeJsonSync = function writeJsonSync(filename, data, options){
if( options && !options.encoding ){
options.encoding='utf8';
}
return fs.writeFileSync(filename, stringify(data, options), options || 'utf8');
};
fs.writeJsonPromise = function writeJsonPromise(filename, data, options){
return fs.writeFilePromise(filename, stringify(data, options), options);
};
/**
* workaround duplicates watch events. options can take a ttl property to modify the default 100ms of ttl for last event.
*/
fs.watchDeduped = function(filename, options, listener){
if ((! listener) && options instanceof Function) {
listener = options;
options = undefined;
}
var ttl = options && options.ttl || 100
, lasttimes = {}
;
return fs.watch(filename, options || {}, function(eventName, fileName){
var now = (new Date()).getTime()
, lasttime = lasttimes[eventName + ':' + fileName] || 0
;
if( now < (lasttime + ttl) ){
return;
}
lasttimes[eventName + ':' + fileName] = now;
listener(eventName, fileName);
});
};
fs.copy = function(source, dest, cb){
var readStream = fs.createReadStream(source)
, writeStream = fs.createWriteStream(dest)
, cbCalled = false
, done = function(err) {
cbCalled || cb(err);
cbCalled = true;
}
;
readStream.on("error", done);
writeStream.on("error", done);
writeStream.on("close", function() {
done();
});
readStream.pipe(writeStream);
};
fs.copyPromise = D.nodeCapsule(fs, fs.copy);
module.exports = fs;