forked from log4js-node/streamroller
/
RollingFileWriteStream.js
271 lines (245 loc) · 8.39 KB
/
RollingFileWriteStream.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
const debug = require("debug")("streamroller:RollingFileWriteStream");
const fs = require("fs-extra");
const path = require("path");
const newNow = require("./now");
const format = require("date-format");
const { Writable } = require("stream");
const fileNameFormatter = require("./fileNameFormatter");
const fileNameParser = require("./fileNameParser");
const moveAndMaybeCompressFile = require("./moveAndMaybeCompressFile");
/**
* RollingFileWriteStream is mainly used when writing to a file rolling by date or size.
* RollingFileWriteStream inherits from stream.Writable
*/
class RollingFileWriteStream extends Writable {
/**
* Create a RollingFileWriteStream
* @constructor
* @param {string} filePath - The file path to write.
* @param {object} options - The extra options
* @param {number} options.numToKeep - The max numbers of files to keep.
* @param {number} options.maxSize - The maxSize one file can reach. Unit is Byte.
* This should be more than 1024. The default is Number.MAX_SAFE_INTEGER.
* @param {string} options.mode - The mode of the files. The default is '0644'. Refer to stream.writable for more.
* @param {string} options.flags - The default is 'a'. Refer to stream.flags for more.
* @param {boolean} options.compress - Whether to compress backup files.
* @param {boolean} options.keepFileExt - Whether to keep the file extension.
* @param {string} options.pattern - The date string pattern in the file name.
* @param {boolean} options.alwaysIncludePattern - Whether to add date to the name of the first file.
*/
constructor(filePath, options) {
debug(`constructor: creating RollingFileWriteStream. path=${filePath}`);
super(options);
this.options = this._parseOption(options);
this.fileObject = path.parse(filePath);
if (this.fileObject.dir === "") {
this.fileObject = path.parse(path.join(process.cwd(), filePath));
}
this.fileFormatter = fileNameFormatter({
file: this.fileObject,
alwaysIncludeDate: this.options.alwaysIncludePattern,
needsIndex: this.options.maxSize < Number.MAX_SAFE_INTEGER,
compress: this.options.compress,
keepFileExt: this.options.keepFileExt
});
this.fileNameParser = fileNameParser({
file: this.fileObject,
keepFileExt: this.options.keepFileExt,
pattern: this.options.pattern
});
this.state = {
currentSize: 0
};
if (this.options.pattern) {
this.state.currentDate = format(this.options.pattern, newNow());
}
this.filename = this.fileFormatter({
index: 0,
date: this.state.currentDate
});
if (["a", "a+", "as", "as+"].includes(this.options.flags)) {
this._setExistingSizeAndDate();
}
debug(
`constructor: create new file ${this.filename}, state=${JSON.stringify(
this.state
)}`
);
this._renewWriteStream();
}
_setExistingSizeAndDate() {
try {
const stats = fs.statSync(this.filename);
this.state.currentSize = stats.size;
if (this.options.pattern) {
this.state.currentDate = format(this.options.pattern, stats.mtime);
}
} catch (e) {
//file does not exist, that's fine - move along
return;
}
}
_parseOption(rawOptions) {
const defaultOptions = {
maxSize: Number.MAX_SAFE_INTEGER,
numToKeep: Number.MAX_SAFE_INTEGER,
encoding: "utf8",
mode: parseInt("0644", 8),
flags: "a",
compress: false,
keepFileExt: false,
alwaysIncludePattern: false
};
const options = Object.assign({}, defaultOptions, rawOptions);
if (options.maxSize <= 0) {
throw new Error(`options.maxSize (${options.maxSize}) should be > 0`);
}
if (options.numToKeep <= 0) {
throw new Error(`options.numToKeep (${options.numToKeep}) should be > 0`);
}
debug(
`_parseOption: creating stream with option=${JSON.stringify(options)}`
);
return options;
}
_final(callback) {
this.currentFileStream.end("", this.options.encoding, callback);
}
_write(chunk, encoding, callback) {
this._shouldRoll().then(() => {
debug(
`_write: writing chunk. ` +
`file=${this.currentFileStream.path} ` +
`state=${JSON.stringify(this.state)} ` +
`chunk=${chunk}`
);
this.currentFileStream.write(chunk, encoding, e => {
this.state.currentSize += chunk.length;
callback(e);
});
});
}
async _shouldRoll() {
if (this._dateChanged() || this._tooBig()) {
debug(
`_shouldRoll: rolling because dateChanged? ${this._dateChanged()} or tooBig? ${this._tooBig()}`
);
await this._roll();
}
}
_dateChanged() {
return (
this.state.currentDate &&
this.state.currentDate !== format(this.options.pattern, newNow())
);
}
_tooBig() {
return this.state.currentSize >= this.options.maxSize;
}
_roll() {
debug(`_roll: closing the current stream`);
return new Promise((resolve, reject) => {
this.currentFileStream.end("", this.options.encoding, () => {
this._moveOldFiles()
.then(resolve)
.catch(reject);
});
});
}
async _moveOldFiles() {
const files = await this._getExistingFiles();
const todaysFiles = this.state.currentDate
? files.filter(f => f.date === this.state.currentDate)
: files;
for (let i = todaysFiles.length; i >= 0; i--) {
debug(`_moveOldFiles: i = ${i}`);
const sourceFilePath = this.fileFormatter({
date: this.state.currentDate,
index: i
});
const targetFilePath = this.fileFormatter({
date: this.state.currentDate,
index: i + 1
});
const moveAndCompressOptions = {
compress: this.options.compress && i === 0,
mode: this.options.mode
}
await moveAndMaybeCompressFile(
sourceFilePath,
targetFilePath,
moveAndCompressOptions
);
}
this.state.currentSize = 0;
this.state.currentDate = this.state.currentDate
? format(this.options.pattern, newNow())
: null;
debug(
`_moveOldFiles: finished rolling files. state=${JSON.stringify(
this.state
)}`
);
this._renewWriteStream();
// wait for the file to be open before cleaning up old ones,
// otherwise the daysToKeep calculations can be off
await new Promise((resolve, reject) => {
this.currentFileStream.write("", "utf8", () => {
this._clean()
.then(resolve)
.catch(reject);
});
});
}
// Sorted from the oldest to the latest
async _getExistingFiles() {
const files = await fs.readdir(this.fileObject.dir).catch(() => []);
debug(`_getExistingFiles: files=${files}`);
const existingFileDetails = files
.map(n => this.fileNameParser(n))
.filter(n => n);
const getKey = n =>
(n.timestamp ? n.timestamp : newNow().getTime()) - n.index;
existingFileDetails.sort((a, b) => getKey(a) - getKey(b));
return existingFileDetails;
}
_renewWriteStream() {
fs.ensureDirSync(this.fileObject.dir);
const filePath = this.fileFormatter({
date: this.state.currentDate,
index: 0
});
const ops = {
flags: this.options.flags,
encoding: this.options.encoding,
mode: this.options.mode
};
this.currentFileStream = fs.createWriteStream(filePath, ops);
this.currentFileStream.on("error", e => {
this.emit("error", e);
});
}
async _clean() {
const existingFileDetails = await this._getExistingFiles();
debug(
`_clean: numToKeep = ${this.options.numToKeep}, existingFiles = ${existingFileDetails.length}`
);
debug("_clean: existing files are: ", existingFileDetails);
if (this._tooManyFiles(existingFileDetails.length)) {
const fileNamesToRemove = existingFileDetails
.slice(0, existingFileDetails.length - this.options.numToKeep - 1)
.map(f => path.format({ dir: this.fileObject.dir, base: f.filename }));
await deleteFiles(fileNamesToRemove);
}
}
_tooManyFiles(numFiles) {
return this.options.numToKeep > 0 && numFiles > this.options.numToKeep;
}
}
const deleteFiles = fileNames => {
debug(`deleteFiles: files to delete: ${fileNames}`);
return Promise.all(fileNames.map(f => fs.unlink(f).catch((e) => {
debug(`deleteFiles: error when unlinking ${f}, ignoring. Error was ${e}`);
})));
};
module.exports = RollingFileWriteStream;