-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfunctions.js
70 lines (64 loc) · 1.84 KB
/
functions.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
var Q = require('q')
, fs = require('fs')
, path = require('path')
, exports = module.exports = {}
;
exports.readJSONFile = function(filePath){
var deferred = Q.defer();
fs.readFile(filePath, function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
try{
text = JSON.parse(text);
deferred.resolve(text);
}catch(error){
deferred.reject('Invalid JSON');
}
}
});
return deferred.promise;
};
exports.readDir = function(dirPath, fileExtension){
var deferred = Q.defer();
fs.readdir(dirPath, function(error, filesList){
if (error) {
deferred.reject(new Error(dirPath + ': ' + error));
} else {
filesList = filesList.filter(function(file){
return path.extname(file) == fileExtension;
}).map(function(file){
return dirPath + '/' + file;
});
deferred.resolve(filesList);
}
});
return deferred.promise;
};
exports.pushContentFiles = function(filesList){
var deferred = Q.defer()
, contentDir = [];
filesList.forEach(function(file) {
exports.readJSONFile(file)
.then(function(content){
contentDir.push(content);
if(contentDir.length == filesList.length){
deferred.resolve( contentDir );
}
})
.catch(function(){
deferred.reject(new Error(file + ': reading file'));
})
});
return deferred.promise;
};
exports.reply = function(request, response, status, header, content, filePath){
if(!response.finished){
response.writeHead(status, header);
if(content){
response.write(content.toString());
}
response.end();
console.log(" -> " + request.method + " " + serverUrl + request.url + ' ' + (status > 299 ? status.toString().red : status.toString().green) + (filePath ? ' -> ' + filePath.cyan : ''));
}
};