-
Notifications
You must be signed in to change notification settings - Fork 0
/
creater.js
68 lines (64 loc) · 2.04 KB
/
creater.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
/*
* @Author: abnerCrack
* @Date: 2016-08-31 17:41:09
* @Last Modified 2016-09-29
* @Last Modified time: 2016-09-29 12:46:39
*/
/*
Usage:
console.log(FileManager.ensureDirectoryExistence('data/dada/data/data/a.json'))
console.log(FileManager.ensureFileExistence('{aaa:2222}','data/dada/data/data/a.json'))
*/
'use strict';
//根据请求 去创建目录层级以及文件
const fs = require('fs')
const path = require('path')
class fileManager {
constructor(filePath, name, schema) {} * directoryExists(path) {
try {
return fs.statSync(path).isDirectory();
} catch (err) {
return false;
}
}
//mkdir
* ensureDirectoryExistence(filePath) {
let dirname = path.dirname(filePath);
if (yield this.directoryExists(dirname)) {
return true;
}
console.log(dirname)
yield this.ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
//has dir
* fileExists(filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (err) {
return false;
}
}
//写入文件
* ensureFileExistence(context, filePath) {
let schemaBuffer = new Buffer(JSON.stringify(context));
let basename = path.basename(filePath)
let state = yield this.fileExists(filePath)
if (!state) {
fs.writeFileSync(filePath, '', { 'flags': 'w+' }, function(err) {
console.log(err)
})
}
let writerStream = fs.createWriteStream(filePath);
writerStream.write(schemaBuffer, 'UTF8');
writerStream.end();
writerStream.on('finish', function() {
console.log("write finish");
});
writerStream.on('error', function(err) {
return err;
});
return true;
}
}
module.exports = new fileManager();