UNPKG

5.79 kBJavaScriptView Raw
1// Nodejs libs.
2var fs = require('fs');
3var path = require('path');
4var chalk = require('chalk');
5
6// The module to be exported.
7var file = module.exports = {};
8var pathSeparatorRe = /[\/\\]/g;
9
10// Like mkdir -p. Create a directory and any intermediary directories.
11file.mkdir = function(dirpath, mode) {
12 // Set directory mode in a strict-mode-friendly way.
13 if (mode == null) {
14 mode = parseInt('0777', 8) & (~process.umask());
15 }
16 dirpath.split(pathSeparatorRe).reduce(function(parts, part) {
17 parts += part + '/';
18 var subpath = path.resolve(parts);
19 if (!file.exists(subpath)) {
20 try {
21 fs.mkdirSync(subpath, mode);
22 } catch(e) {
23 throw console.error('Unable to create directory "' + subpath + '" (Error code: ' + e.code + ').', e);
24 }
25 }
26 return parts;
27 }, '');
28};
29
30// The default file encoding to use.
31file.defaultEncoding = 'utf8';
32// Whether to preserve the BOM on file.read rather than strip it.
33file.preserveBOM = false;
34
35// Read a file, return its contents.
36file.read = function(filepath) {
37 var contents;
38 try {
39 contents = fs.readFileSync(String(filepath)).toString();
40 // console.log('Reading "' + filepath + '" successful');
41 return contents;
42 } catch(e) {
43 console.error('Unable to read "' + filepath + '" file (Error code: ' + e.code + ').');
44 }
45};
46
47// Write a file.
48file.write = function(filepath, contents) {
49 // Create path, if necessary.
50 file.mkdir(path.dirname(filepath));
51 try {
52 // If contents is already a Buffer, don't try to encode it. If no encoding
53 // was specified, use the default.
54 if(!Buffer.isBuffer(contents)){
55 contents = new Buffer(contents);
56 }
57 // Actually write file.
58 fs.writeFileSync(filepath, contents);
59 console.log('Write "'+chalk.green(filepath)+'" successful');
60 return true;
61 } catch(e) {
62 console.error('Unable to write "' + chalk.red.bold(filepath) + '" file (Error code: ' + e.code + ').');
63 }
64};
65
66// Read a file, optionally processing its content, then write the output.
67file.copy = function(srcpath, destpath) {
68 // Actually read the file.
69 if(file.isDir(srcpath)){
70 file.mkdir(destpath);
71 return;
72 }
73 var contents = file.read(srcpath);
74 // Abort copy if the process function returns false.
75 if (contents === false) {
76 console.error('Write aborted.');
77 } else {
78 file.write(destpath, contents);
79 }
80};
81
82// True if the file path exists.
83file.exists = function() {
84 var filepath = path.join.apply(path, arguments);
85 return fs.existsSync(filepath);
86};
87
88// True if the file is a symbolic link.
89file.isLink = function() {
90 var filepath = path.join.apply(path, arguments);
91 return file.exists(filepath) && fs.lstatSync(filepath).isSymbolicLink();
92};
93
94// True if the path is a directory.
95file.isDir = function() {
96 var filepath = path.join.apply(path, arguments);
97 return file.exists(filepath) && fs.statSync(filepath).isDirectory();
98};
99
100// True if the path is a file.
101file.isFile = function() {
102 var filepath = path.join.apply(path, arguments);
103 return file.exists(filepath) && fs.statSync(filepath).isFile();
104};
105
106// Is a given file path absolute?
107file.isPathAbsolute = function() {
108 var filepath = path.join.apply(path, arguments);
109 return path.resolve(filepath) === filepath.replace(/[\/\\]+$/, '');
110};
111
112
113// Do all the specified paths refer to the same path?
114file.arePathsEquivalent = function(first) {
115 first = path.resolve(first);
116 for (var i = 1; i < arguments.length; i++) {
117 if (first !== path.resolve(arguments[i])) { return false; }
118 }
119 return true;
120};
121
122// Are descendant path(s) contained within ancestor path? Note: does not test
123// if paths actually exist.
124file.doesPathContain = function(ancestor) {
125 ancestor = path.resolve(ancestor);
126 var relative;
127 for (var i = 1; i < arguments.length; i++) {
128 relative = path.relative(path.resolve(arguments[i]), ancestor);
129 if (relative === '' || /\w+/.test(relative)) { return false; }
130 }
131 return true;
132};
133
134// Test to see if a filepath is the CWD.
135file.isPathCwd = function() {
136 var filepath = path.join.apply(path, arguments);
137 try {
138 return file.arePathsEquivalent(process.cwd(), fs.realpathSync(filepath));
139 } catch(e) {
140 return false;
141 }
142};
143
144// Test to see if a filepath is contained within the CWD.
145file.isPathInCwd = function() {
146 var filepath = path.join.apply(path, arguments);
147 try {
148 return file.doesPathContain(process.cwd(), fs.realpathSync(filepath));
149 } catch(e) {
150 return false;
151 }
152};
153
154
155//Return an array of all files in directory
156file.getFilesInDirectory = function(dir){
157 var self = file,
158 results = [],
159 basePath = process.cwd();
160
161 dir = path.resolve(basePath, dir);
162 try{
163 list = fs.readdirSync(dir);
164 if(list.length === 0){
165 results.push(dir);
166 console.log('The directory"'+dir+'" is null');
167 return results;
168 }else{
169 list.forEach(function(file){
170 file = path.resolve(dir, file);
171 fileStat = fs.statSync(file);
172 if(fileStat && fileStat.isDirectory()){
173 subResults = self.getFilesInDirectory(file);
174 results = results.concat(subResults);
175 }else{
176 results.push(file);
177 }
178 });
179 }
180 }catch(e){
181 console.error('Unable read directory"'+dir+'" file (' + e.message + ').')
182 }
183 return results;
184};
185
186
187file.deleteDirectory = function(path){
188 if(file.exists(path)){
189 fs.readdirSync(path).forEach(function(item, index){
190 var curPath = path+'/'+item;
191 if(fs.lstatSync(curPath).isDirectory()){
192 file.deleteDirectory(curPath);
193 }else{
194 fs.unlinkSync(curPath);
195 }
196 });
197 fs.rmdirSync(path);
198 }
199};
200
201file.unixifyPath = function(filepath) {
202 if (process.platform === 'win32') {
203 return filepath.replace(/\\{1,2}/g, "/");
204 } else {
205 return filepath;
206 }
207};
\No newline at end of file