2 var BaseRollingFileStream = require('./BaseRollingFileStream')
3 , debug = require('../debug')('DateRollingFileStream')
4 , format = require('../date_format')
6 , util = require('util');
8 module.exports = DateRollingFileStream;
10 function findTimestampFromFileIfExists(filename, now) {
11 return fs.existsSync(filename) ? fs.statSync(filename).mtime : new Date(now());
14 function DateRollingFileStream(filename, pattern, options, now) {
15 debug("Now is " + now);
16 if (pattern && typeof(pattern) === 'object') {
21 this.pattern = pattern || '.yyyy-MM-dd';
22 this.now = now || Date.now;
23 this.lastTimeWeWroteSomething = format.asString(
25 findTimestampFromFileIfExists(filename, this.now)
28 this.baseFilename = filename;
29 this.alwaysIncludePattern = false;
32 if (options.alwaysIncludePattern) {
33 this.alwaysIncludePattern = true;
34 filename = this.baseFilename + this.lastTimeWeWroteSomething;
36 delete options.alwaysIncludePattern;
37 if (Object.keys(options).length === 0) {
41 debug("this.now is " + this.now + ", now is " + now);
43 DateRollingFileStream.super_.call(this, filename, options);
45 util.inherits(DateRollingFileStream, BaseRollingFileStream);
47 DateRollingFileStream.prototype.shouldRoll = function() {
48 var lastTime = this.lastTimeWeWroteSomething,
49 thisTime = format.asString(this.pattern, new Date(this.now()));
51 debug("DateRollingFileStream.shouldRoll with now = " +
52 this.now() + ", thisTime = " + thisTime + ", lastTime = " + lastTime);
54 this.lastTimeWeWroteSomething = thisTime;
55 this.previousTime = lastTime;
57 return thisTime !== lastTime;
60 DateRollingFileStream.prototype.roll = function(filename, callback) {
63 debug("Starting roll");
65 if (this.alwaysIncludePattern) {
66 this.filename = this.baseFilename + this.lastTimeWeWroteSomething;
67 this.closeTheStream(this.openTheStream.bind(this, callback));
69 var newFilename = this.baseFilename + this.previousTime;
71 deleteAnyExistingFile.bind(null,
72 renameTheCurrentFile.bind(null,
73 this.openTheStream.bind(this,
77 function deleteAnyExistingFile(cb) {
78 //on windows, you can get a EEXIST error if you rename a file to an existing file
79 //so, we'll try to delete the file we're renaming to first
80 fs.unlink(newFilename, function (err) {
81 //ignore err: if we could not delete, it's most likely that it doesn't exist
86 function renameTheCurrentFile(cb) {
87 debug("Renaming the " + filename + " -> " + newFilename);
88 fs.rename(filename, newFilename, cb);