BaseRollingFileStream.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. that.theStream.write(chunk, encoding, callback);
  45. }
  46. debug("in _write");
  47. if (this.shouldRoll()) {
  48. this.currentSize = 0;
  49. this.roll(this.filename, writeTheChunk);
  50. } else {
  51. writeTheChunk();
  52. }
  53. };
  54. BaseRollingFileStream.prototype.openTheStream = function(cb) {
  55. debug("opening the underlying stream");
  56. this.theStream = fs.createWriteStream(this.filename, this.options);
  57. if (cb) {
  58. this.theStream.on("open", cb);
  59. }
  60. };
  61. BaseRollingFileStream.prototype.closeTheStream = function(cb) {
  62. debug("closing the underlying stream");
  63. this.theStream.end(cb);
  64. };
  65. BaseRollingFileStream.prototype.shouldRoll = function() {
  66. return false; // default behaviour is never to roll
  67. };
  68. BaseRollingFileStream.prototype.roll = function(filename, callback) {
  69. callback(); // default behaviour is not to do anything
  70. };