-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
114 lines (101 loc) · 2.6 KB
/
index.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const fs = require('fs');
class FileMaker {
constructor(spec = {commentPattern: '//', header: null, footer: null}) {
let empty = '';
this.buffer = empty;
this.commentPattern = empty;
this.header = empty;
this.footer = empty;
if (typeof spec === 'string') {
this.buffer = spec;
} else if (typeof spec === 'object') {
this.commentPattern = spec.commentPattern || empty;
this.header = spec.header || empty;
this.footer = spec.footer || empty;
}
}
/**
* Write indent characters to the buffer (tabs)
* @param {int} [indents=1] - The number of indents. Defaults to 1.
*/
indent(indents = 1) {
if (indents > 0) {
for (let i = 0; i < indents; i++) {
this.write('\t');
}
}
}
/**
* Sets a header for the buffer
* @param {string} header - The header
*/
setHeader(header) {
this.header = header;
};
/**
* Sets the footer for the buffer
* @param {string} footer - The footer
*/
setFooter(footer) {
this.footer = footer;
};
/**
* Writes to the buffer
* @param {string} line - The value to write
*/
write(line) {
this.buffer += line;
}
/**
* Writes a new line to the buffer
* @param {string} [line=''] - The line to write
* @param {int} [indent=0] - The number of indents for this line. Defaults to 0
*/
writeLine(line = '', indent = 0) {
this.indent(indent);
this.write(`${line}\n`);
}
/**
* Writes a comment to the buffer
* @param {string} comment - The comment
*/
writeComment(comment) {
this.write(`${this.commentPattern} ${comment}`);
}
/**
* Writes a new comment section to the buffer. Helpful to compartmentalise the file.
* @param {string} heading - The section heading
* @param {number} [indent=0] - Indents for the heading. Defaults to 0.
*/
writeNewSection(heading, indent = 0) {
this.write('\n\n');
this.indent(indent);
this.write(`${this.commentPattern} ${heading}\n`);
this.indent(indent);
this.write(`${this.commentPattern} --------------------------------\n\n`);
};
/**
* Returns the current buffer to a string including headers and footers
* @returns {string}
*/
toString() {
return `${this.header}\n${this.buffer}\n${this.footer}`;
}
/**
* Saves the current buffer to a file including headers and footers
* @param {string} path - The path to save the file to
* @param {function} onError - Callback for any errors encountered while saving the file
*/
saveTo(path, onError) {
fs.writeFile(path, this.toString(), function (err) {
if(err) {
if (typeof onError === 'function') {
onError(err);
} else {
throw(err);
}
}
});
}
}
module.exports = FileMaker;