Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / log4js / lib / streams / BaseRollingFileStream.js
1 "use strict";
2 var fs = require('fs')
3 , stream
4 , debug = require('../debug')('BaseRollingFileStream')
5 , util = require('util')
6 , semver = require('semver');
7
8 if (semver.satisfies(process.version, '>=0.10.0')) {
9   stream = require('stream');
10 } else {
11   stream = require('readable-stream');
12 }
13
14 module.exports = BaseRollingFileStream;
15
16 function BaseRollingFileStream(filename, options) {
17   debug("In BaseRollingFileStream");
18   this.filename = filename;
19   this.options = options || {};
20   this.options.encoding = this.options.encoding || 'utf8';
21   this.options.mode = this.options.mode || parseInt('0644', 8);
22   this.options.flags = this.options.flags || 'a';
23
24   this.currentSize = 0;
25   
26   function currentFileSize(file) {
27     var fileSize = 0;
28     try {
29       fileSize = fs.statSync(file).size;
30     } catch (e) {
31       // file does not exist
32     }
33     return fileSize;
34   }
35
36   function throwErrorIfArgumentsAreNotValid() {
37     if (!filename) {
38       throw new Error("You must specify a filename");
39     }
40   }
41
42   throwErrorIfArgumentsAreNotValid();
43   debug("Calling BaseRollingFileStream.super");
44   BaseRollingFileStream.super_.call(this);
45   this.openTheStream();
46   this.currentSize = currentFileSize(this.filename);
47 }
48 util.inherits(BaseRollingFileStream, stream.Writable);
49
50 BaseRollingFileStream.prototype._write = function(chunk, encoding, callback) {
51   var that = this;
52   function writeTheChunk() {
53     debug("writing the chunk to the underlying stream");
54     that.currentSize += chunk.length;
55     try {
56       that.theStream.write(chunk, encoding, callback);
57     }
58     catch (err){
59       debug(err);
60       callback();
61     }
62   }
63
64   debug("in _write");
65
66   if (this.shouldRoll()) {
67     this.currentSize = 0;
68     this.roll(this.filename, writeTheChunk);
69   } else {
70     writeTheChunk();
71   }
72 };
73
74 BaseRollingFileStream.prototype.openTheStream = function(cb) {
75   debug("opening the underlying stream");
76   this.theStream = fs.createWriteStream(this.filename, this.options);
77   if (cb) {
78     this.theStream.on("open", cb);
79   }
80 };
81
82 BaseRollingFileStream.prototype.closeTheStream = function(cb) {
83   debug("closing the underlying stream");
84   this.theStream.end(cb);
85 };
86
87 BaseRollingFileStream.prototype.shouldRoll = function() {
88   return false; // default behaviour is never to roll
89 };
90
91 BaseRollingFileStream.prototype.roll = function(filename, callback) {
92   callback(); // default behaviour is not to do anything
93 };
94