File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed
Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ var Stream = require ( 'stream' ) ,
2+ FileLogStream = require ( './filelogstream' ) ;
3+
4+ var format = function ( d ) {
5+ return 'log: ' + d + '\n' ;
6+ } ;
7+
8+ var logger = new FileLogStream ( './log.txt' , { formatLog : format } ) ;
9+
10+ var s = new Stream ( ) ;
11+ s . pipe ( logger ) ;
12+ s . emit ( 'data' , 'message 1' ) ;
13+ s . emit ( 'data' , 'message 2' ) ;
14+ s . emit ( 'data' , 'message 3' ) ;
15+ s . emit ( 'end' ) ;
Original file line number Diff line number Diff line change 1+ var Stream = require ( 'stream' ) ,
2+ util = require ( 'util' ) ,
3+ fs = require ( 'fs' ) ;
4+
5+ var FileLogStream = function ( filepath , opts ) {
6+ opts = opts || { } ;
7+
8+ this . _fileStream = fs . createWriteStream ( filepath , opts ) ;
9+ this . readable = true ;
10+ this . writable = true ;
11+
12+ var fileWrite , formatLog ;
13+ if ( typeof opts . formatLog === 'function' ) {
14+ formatLog = opts . formatLog ;
15+ fileWrite = this . _fileStream . write ;
16+ this . _fileStream . write = function ( data ) {
17+ data = formatLog ( data ) ;
18+ return fileWrite . call ( this , data ) ;
19+ } ;
20+ }
21+
22+ this . on ( 'pipe' , function ( readStream ) {
23+ readStream . pipe ( this . _fileStream ) ;
24+ } ) ;
25+ } ;
26+ util . inherits ( FileLogStream , Stream ) ;
27+ FileLogStream . prototype . write = function ( data ) {
28+ this . emit ( 'data' , data ) ;
29+ return true ;
30+ } ;
31+ FileLogStream . prototype . end = function ( data ) {
32+ if ( data ) { this . write ( data ) ; }
33+
34+ this . _fileStream . end ( ) ;
35+ this . emit ( 'end' ) ;
36+ } ;
37+
38+ module . exports = FileLogStream ;
You can’t perform that action at this time.
0 commit comments