BaseRollingFileStream.js 2.2 KB

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